¿Cómo puedo obtener el carácter ascii de un código ascii dado?
Por ejemplo, estoy buscando un método que, dado el código 65, devolvería "A".
Gracias
Respuestas:
¿Quiere decir "A" (a string) o "A" (a char)?
int unicode = 65;
char character = (char) unicode;
string text = character.ToString();
Tenga en cuenta que me he referido a Unicode en lugar de ASCII ya que esa es la codificación de caracteres nativa de C #; esencialmente cada uno chares un punto de código UTF-16.
string c = Char.ConvertFromUtf32(65);
c contendrá "A"
Hay varias formas de hacer esto.
Usando char struct (para encadenar y viceversa)
string _stringOfA = char.ConvertFromUtf32(65);
int _asciiOfA = char.ConvertToUtf32("A", 0);
Simplemente lanzando el valor (se muestra el carácter y la cadena)
char _charA = (char)65;
string _stringA = ((char)65).ToString();
Usando ASCIIEncoding.
Esto se puede usar en un bucle para hacer una matriz completa de bytes
var _bytearray = new byte[] { 65 };
ASCIIEncoding _asiiencode = new ASCIIEncoding();
string _alpha = _asiiencode .GetString(_newByte, 0, 1);
Puede anular la clase de convertidor de tipos, esto le permitiría hacer una validación elegante de los valores:
var _converter = new ASCIIConverter();
string _stringA = (string)_converter.ConvertFrom(65);
int _intOfA = (int)_converter.ConvertTo("A", typeof(int));
Aquí está la clase:
public class ASCIIConverter : TypeConverter
{
// Overrides the CanConvertFrom method of TypeConverter.
// The ITypeDescriptorContext interface provides the context for the
// conversion. Typically, this interface is used at design time to
// provide information about the design-time container.
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(int))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
// Overrides the ConvertFrom method of TypeConverter.
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is int)
{
//you can validate a range of int values here
//for instance
//if (value >= 48 && value <= 57)
//throw error
//end if
return char.ConvertFromUtf32(65);
}
return base.ConvertFrom(context, culture, value);
}
// Overrides the ConvertTo method of TypeConverter.
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(int))
{
return char.ConvertToUtf32((string)value, 0);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
También se puede hacer de otra manera
byte[] pass_byte = Encoding.ASCII.GetBytes("your input value");
y luego imprima el resultado. utilizando foreachloop.
Aquí hay una función que funciona para los 256 bytes y garantiza que verá un carácter para cada valor:
static char asciiSymbol( byte val )
{
if( val < 32 ) return '.'; // Non-printable ASCII
if( val < 127 ) return (char)val; // Normal ASCII
// Workaround the hole in Latin-1 code page
if( val == 127 ) return '.';
if( val < 0x90 ) return "€.‚ƒ„…†‡ˆ‰Š‹Œ.Ž."[ val & 0xF ];
if( val < 0xA0 ) return ".‘’“”•–—˜™š›œ.žŸ"[ val & 0xF ];
if( val == 0xAD ) return '.'; // Soft hyphen: this symbol is zero-width even in monospace fonts
return (char)val; // Normal Latin-1
}
Simplemente prueba esto:
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
Creo que un elenco simple puede funcionar
int ascii = (int) "A"
stringa int. Si lo fuera 'A', funcionaría, pero el elenco sería redundante ya que hay una conversión implícita de chara int.
Lo siento, no sé Java, pero me enfrenté al mismo problema esta noche, así que escribí esto (está en c #)
public string IncrementString(string inboundString) {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(inboundString.ToArray);
bool incrementNext = false;
for (l = -(bytes.Count - 1); l <= 0; l++) {
incrementNext = false;
int bIndex = Math.Abs(l);
int asciiVal = Conversion.Val(bytes(bIndex).ToString);
asciiVal += 1;
if (asciiVal > 57 & asciiVal < 65)
asciiVal = 65;
if (asciiVal > 90) {
asciiVal = 48;
incrementNext = true;
}
bytes(bIndex) = System.Text.Encoding.ASCII.GetBytes({ Strings.Chr(asciiVal) })(0);
if (incrementNext == false)
break; // TODO: might not be correct. Was : Exit For
}
inboundString = System.Text.Encoding.ASCII.GetString(bytes);
return inboundString;
}