2009-04-06 7 views
25

VB ha un paio di funzioni native per convertire un char in un valore ASCII e viceversa - Asc() e Chr().Qual è l'equivalente delle funzioni Asc() e Chr() di VB in C#?

Ora ho bisogno di ottenere la funzionalità equivalente in C#. Qual è il modo migliore?

+4

prega di notare che raramente qualcuno parla di valori ASCII in questi giorni. Di solito si utilizzano invece codepoint Unicode (o codifica UTF-16): http://www.joelonsoftware.com/articles/Unicode.html –

+5

VB.Net Asc * non restituisce i codici ASCII, * né * restituisce i codici Unicode. Esso [restituisce] (http://msdn.microsoft.com/en-us/library/zew1e4wc (v = vs.71) .aspx) codici "ANSI" nella tabella codici di Windows corrente. – MarkJ

+0

@MarkJ Questo è proprio come VB6; vai a capire! –

risposta

26

Si può sempre aggiungere un riferimento a Microsoft.VisualBasic e quindi utilizzare gli stessi metodi esatti: Strings.Chr e Strings.Asc.

Questo è il modo più semplice per ottenere la stessa identica funzionalità.

+2

Se aggiungi un riferimento, esisterà. – Samuel

+4

+1 In realtà ** essendo a destra **, a differenza di * tutti * le altre risposte. Usano * diverse * codifiche da VB Asc e Chr e sono * errati *. – MarkJ

+0

@MarkJ: Sospetto che gli usi più comuni di 'Asc' e' Chr' utilizzino valori nell'intervallo 0-126, che il programmatore si aspetterebbe di associare ai corrispondenti punti di codice Unicode; anche se esistesse un sistema in cui, ad esempio, Chr (34) restituisse "" piuttosto che "", penserei che il programmatore che ha scritto 'Chr (34)' abbia probabilmente inteso '". – supercat

18

Per Asc() si può lanciare il char a un int come questo:

int i = (int)your_char; 

e per Chr() si può lanciare di nuovo ad un char da un int come questo:

char c = (char)your_int; 

Ecco un piccolo programma che dimostra il tutto:

using System; 

class Program 
{ 
    static void Main() 
    { 
     char c = 'A'; 
     int i = 65; 

     // both print "True" 
     Console.WriteLine(i == (int)c); 
     Console.WriteLine(c == (char)i); 
    } 
} 
+11

-1 perché è * errato *. VB.Net Asc * non restituisce i codici ASCII, * né * restituisce i codici Unicode. Esso [restituisce] (http://msdn.microsoft.com/en-us/library/zew1e4wc (v = vs.71) .aspx) i codici "ANSI" nella pagina di codice corrente di Windows (cioè dipende dalla locale corrente del thread) . Il cast restituirà un punto di codice Unicode. Diverso per la maggior parte dei personaggi sulla maggior parte dei locali. Usa Microsoft.VisualBasic.Strings.Asc e Chr. – MarkJ

+1

Sono d'accordo con @MarkJ - Ho provato questo codice e restituisce gli stessi risultati per alcuni caratteri (a-z, per esempio) ma risultati diversi per gli altri ("<", ecc.). – JDB

+0

Sì, i risultati non sono gli stessi: {caso 1. Strings.Chr (128) risultato 1: 8364 '€'} {caso 2. (char) 128 risultato 2: 128 '(un valore casella)'} Inoltre, nel 2 ° caso qualsiasi valore superiore a 128 restituisce 'un valore di scatola' invece di un carattere valido. – Sadiq

2

Per Chr() si può usare:

char chr = (char)you_char_value; 
0

Dato char c e int i, e le funzioni di fi (int) e FC (char):

da char a int (analogico di VB Asc()): esegue espressamente il cast come int: i = (int) c;

o cast espressamente (promozione): fi (c), i + = c;

Da int a char (analogico di VB Chr()):

gettato esplicitamente l'int come char: c = (char) i, fc ((char) i);

Un cast implicita non è consentita, come un int è più ampio (ha una più ampia gamma di valori) di un char

0

Strings.Asc non è equivalente a un cast normale in C# per caratteri non ASCII che possono andare oltre il valore di codice 127. La risposta che ho trovato su https://social.msdn.microsoft.com/Forums/vstudio/en-US/13fec271-9a97-4b71-ab28-4911ff3ecca0/equivalent-in-c-of-asc-chr-functions-of-vb?forum=csharpgeneral ammonta a qualcosa di simile:

static int Asc(char c) 
    { 
     int converted = c; 
     if (converted >= 0x80) 
     { 
      byte[] buffer = new byte[2]; 
      // if the resulting conversion is 1 byte in length, just use the value 
      if (System.Text.Encoding.Default.GetBytes(new char[] { c }, 0, 1, buffer, 0) == 1) 
      { 
       converted = buffer[0]; 
      } 
      else 
      { 
       // byte swap bytes 1 and 2; 
       converted = buffer[0] << 16 | buffer[1]; 
      } 
     } 
     return converted; 
    } 

Oppure, se si desidera che l'affare lettura aggiungere un riferimento a Microsoft.VisualBasic assemblaggio.

1

Ho questi utilizzando ReSharper, il codice esatto viene eseguito da VB sulla vostra macchina

/// <summary> 
/// Returns the character associated with the specified character code. 
/// </summary> 
/// 
/// <returns> 
/// Returns the character associated with the specified character code. 
/// </returns> 
/// <param name="CharCode">Required. An Integer expression representing the <paramref name="code point"/>, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> &lt; 0 or &gt; 255 for Chr.</exception><filterpriority>1</filterpriority> 
public static char Chr(int CharCode) 
{ 
    if (CharCode < (int) short.MinValue || CharCode > (int) ushort.MaxValue) 
    throw new ArgumentException(Utils.GetResourceString("Argument_RangeTwoBytes1", new string[1] 
    { 
     "CharCode" 
    })); 
    if (CharCode >= 0 && CharCode <= (int) sbyte.MaxValue) 
    return Convert.ToChar(CharCode); 
    try 
    { 
    Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage()); 
    if (encoding.IsSingleByte && (CharCode < 0 || CharCode > (int) byte.MaxValue)) 
     throw ExceptionUtils.VbMakeException(5); 
    char[] chars = new char[2]; 
    byte[] bytes = new byte[2]; 
    Decoder decoder = encoding.GetDecoder(); 
    if (CharCode >= 0 && CharCode <= (int) byte.MaxValue) 
    { 
     bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue)); 
     decoder.GetChars(bytes, 0, 1, chars, 0); 
    } 
    else 
    { 
     bytes[0] = checked ((byte) ((CharCode & 65280) >> 8)); 
     bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue)); 
     decoder.GetChars(bytes, 0, 2, chars, 0); 
    } 
    return chars[0]; 
    } 
    catch (Exception ex) 
    { 
    throw ex; 
    } 
} 


/// <summary> 
/// Returns an Integer value representing the character code corresponding to a character. 
/// </summary> 
/// 
/// <returns> 
/// Returns an Integer value representing the character code corresponding to a character. 
/// </returns> 
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority> 
public static int Asc(char String) 
{ 
    int num1 = Convert.ToInt32(String); 
    if (num1 < 128) 
    return num1; 
    try 
    { 
    Encoding fileIoEncoding = Utils.GetFileIOEncoding(); 
    char[] chars = new char[1] 
    { 
     String 
    }; 
    if (fileIoEncoding.IsSingleByte) 
    { 
     byte[] bytes = new byte[1]; 
     fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0); 
     return (int) bytes[0]; 
    } 
    byte[] bytes1 = new byte[2]; 
    if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1) 
     return (int) bytes1[0]; 
    if (BitConverter.IsLittleEndian) 
    { 
     byte num2 = bytes1[0]; 
     bytes1[0] = bytes1[1]; 
     bytes1[1] = num2; 
    } 
    return (int) BitConverter.ToInt16(bytes1, 0); 
    } 
    catch (Exception ex) 
    { 
    throw ex; 
    } 
} 


/// <summary> 
/// Returns an Integer value representing the character code corresponding to a character. 
/// </summary> 
/// 
/// <returns> 
/// Returns an Integer value representing the character code corresponding to a character. 
/// </returns> 
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority> 
public static int Asc(string String) 
{ 
    if (String == null || String.Length == 0) 
    throw new ArgumentException(Utils.GetResourceString("Argument_LengthGTZero1", new string[1] 
    { 
     "String" 
    })); 
    return Strings.Asc(String[0]); 
} 

Le risorse sono solo memorizzati messaggio di errore, così in qualche modo il modo in cui si desidera ignorarli, e gli altri due metodo che si fa non hanno accesso a sono le seguenti:

internal static Encoding GetFileIOEncoding() 
{ 
    return Encoding.Default; 
} 

internal static int GetLocaleCodePage() 
{ 
    return Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage; 
} 
0
//Char to Int - ASC("]") 
int lIntAsc = (int)Char.Parse("]"); 
Console.WriteLine(lIntAsc); //Return 91 



//Int to Char 

char lChrChar = (char)91; 
Console.WriteLine(lChrChar); //Return "]" 
+1

Benvenuti in Stack Overflow! Anche se questo snippet di codice può risolvere la domanda, [inclusa una spiegazione] (// meta.stackexchange.com/questions/114762/explaining-entely-code-based-answers) aiuta davvero a migliorare la qualità del tuo post. Ricorda che stai rispondendo alla domanda per i lettori in futuro, e queste persone potrebbero non conoscere le ragioni del tuo suggerimento sul codice. Cerca anche di non affollare il tuo codice con commenti esplicativi, in quanto ciò riduce la leggibilità sia del codice che delle spiegazioni! – FrankerZ

+0

'Asc' e' Chr' non implicano ASCII o ISO 8859-1 (che è ciò che fa il tuo codice). Coinvolgono 'Encoding.Default'. –

Problemi correlati