2011-01-10 64 views
46

¿Cómo puedo obtener el carácter ascii de un código ascii dado?Cómo obtener el carácter para un valor de ascii dado

p. Ej. Estoy buscando un método que dado el código 65 devolvería "A".

Gracias

+3

como alguien ha escrito antes, el simple reparto carbón c = (char) 65 obras –

+0

Posible duplicado de [Cómo obtener un Char de un ASCI I Código de personaje en C#] (http: // stackoverflow.com/questions/3414900/how-to-get-a-char-from-an-ascii-character-code-in-c-sharp) –

Respuesta

105

Qué quiere decir "A" (un string) o 'A' (un 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 es C# 's de codificación de caracteres nativo; esencialmente cada char es un punto de código UTF-16.

+0

'A' está bien, gracias – Dunc

+0

@Jon Skeet: si configuro unicode = 128 , por qué no estoy listo para obtener el personaje correspondiente. –

+0

@EthanHunt: Entonces obtendrás U + 0080, que es un personaje de control. Sospecho que estás pensando en 128 en una codificación de caracteres diferente. –

28
string c = Char.ConvertFromUtf32(65); 

c contendrá "A"

-1

creo un molde simple puede trabajar

int ascii = (int) "A"

+0

Ahora quería ayuda con lo opuesto. Obtener un carácter de un número – StefanE

+10

No es que el código dado se compile de todos modos, no se puede convertir de 'cadena' a' int'. Si fuera '' A '', entonces funcionaría, pero el elenco sería redundante ya que hay una conversión * implícita * de 'char' a' int'. –

1

También se puede hacer de otra manera

byte[] pass_byte = Encoding.ASCII.GetBytes("your input value"); 

y luego imprime el resultado. usando foreach loop.

0

Lo siento, no sé de Java, pero me encontré con el mismo problema esta noche, así que escribí esto (que es 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; 
} 
+0

Para obtener todas las combinaciones, simplemente ejecútelo en un bucle. – Matth3w

5

Esto funciona en mi código.

string asciichar = (Convert.ToChar(65)).ToString(); 

de devolución: asciichar = 'A';

+0

Solución más simple –

-1

Aquí es una función que funcione para todos los 256 bytes, y asegura verá un personaje 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 
} 
+0

Si el objetivo era obtener un punto de código Unicode visible para cada punto de código ASCII, entonces se podría usar [Control Pictures] (http://unicode.org/charts/PDF/U2400.pdf) para reemplazar el [C0 Control] (http://unicode.org/charts/PDF/U0000.pdf) personajes. ␀ ␁ ␂ ␃ ␄ ␅ ␆ ␇ ␈ ␉ ␊ ␋ ␌ ␍ ␎ ␏ ... –

+1

@TomBlodget bueno saber, pero eso no es una respuesta a la pregunta del PO. Siéntase libre de enviar otra función C# que haga lo que el OP solicite. – Soonts

+0

Tenga en cuenta que ASCII solo sube a 127. Cualquier cosa por encima simplemente no es ASCII, por lo menos su método tiene un nombre pobre. –

0

Hay algunas maneras de hacer esta.

Usando struct char (a cadena y de vuelta)

string _stringOfA = char.ConvertFromUtf32(65); 

int _asciiOfA = char.ConvertToUtf32("A", 0); 

Simplemente fundición el valor (char y la cadena se muestra)

char _charA = (char)65; 

string _stringA = ((char)65).ToString(); 

Usando ASCIIEncoding.
Esto se puede utilizar en un bucle para hacer toda una serie de bytes

var _bytearray = new byte[] { 65 }; 

ASCIIEncoding _asiiencode = new ASCIIEncoding(); 

string _alpha = _asiiencode .GetString(_newByte, 0, 1); 

Puede sustituir la clase de tipo de convertidor, esto permitirá hacer una validación de fantasía de los valores:

var _converter = new ASCIIConverter(); 

string _stringA = (string)_converter.ConvertFrom(65); 

int _intOfA = (int)_converter.ConvertTo("A", typeof(int)); 

Aquí es 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); 
    } 
} 
Cuestiones relacionadas