[C#] ¿Cómo obtengo una representación de bytes consistente en cadenas en C # sin especificar manualmente una codificación?


Depende de la codificación de su cadena ( ASCII , UTF-8 , ...).

Por ejemplo:

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

Una pequeña muestra por qué la codificación importa:

string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'

ASCII simplemente no está equipado para tratar con caracteres especiales.

Internamente, .NET Framework usa UTF-16 para representar cadenas, por lo que si simplemente desea obtener los bytes exactos que usa .NET, use System.Text.Encoding.Unicode.GetBytes (...) .

Consulte Codificación de caracteres en .NET Framework (MSDN) para obtener más información.


¿Cómo convierto una string en un byte[] en .NET (C #) sin especificar manualmente una codificación específica?

Voy a cifrar la cadena. Puedo encriptarlo sin convertirlo, pero aún me gustaría saber por qué la codificación viene a jugar aquí.

Además, ¿por qué debería tenerse en cuenta la codificación? ¿No puedo simplemente obtener los bytes en los que se ha almacenado la cadena? ¿Por qué hay una dependencia en las codificaciones de caracteres?

simple code with LINQ

string s = "abc"
byte[] b = s.Select(e => (byte)e).ToArray();

EDIT : as commented below, it is not a good way.

but you can still use it to understand LINQ with a more appropriate coding :

string s = "abc"
byte[] b = s.Cast<byte>().ToArray();

Two ways:

public static byte[] StrToByteArray(this string s)
    List<byte> value = new List<byte>();
    foreach (char c in s.ToCharArray())
    return value.ToArray();


public static byte[] StrToByteArray(this string s)
    s = s.Replace(" ", string.Empty);
    byte[] buffer = new byte[s.Length / 2];
    for (int i = 0; i < s.Length; i += 2)
        buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
    return buffer;

I tend to use the bottom one more often than the top, haven't benchmarked them for speed.

The key issue is that a glyph in a string takes 32 bits (16 bits for a character code) but a byte only has 8 bits to spare. A one-to-one mapping doesn't exist unless you restrict yourself to strings that only contain ASCII characters. System.Text.Encoding has lots of ways to map a string to byte[], you need to pick one that avoids loss of information and that is easy to use by your client when she needs to map the byte[] back to a string.

Utf8 is a popular encoding, it is compact and not lossy.

The closest approach to the OP's question is Tom Blodget's, which actually goes into the object and extracts the bytes. I say closest because it depends on implementation of the String Object.

"Can't I simply get what bytes the string has been stored in?"

Sure, but that's where the fundamental error in the question arises. The String is an object which could have an interesting data structure. We already know it does, because it allows unpaired surrogates to be stored. It might store the length. It might keep a pointer to each of the 'paired' surrogates allowing quick counting. Etc. All of these extra bytes are not part of the character data.

What you want is each character's bytes in an array. And that is where 'encoding' comes in. By default you will get UTF-16LE. If you don't care about the bytes themselves except for the round trip then you can choose any encoding including the 'default', and convert it back later (assuming the same parameters such as what the default encoding was, code points, bug fixes, things allowed such as unpaired surrogates, etc.

But why leave the 'encoding' up to magic? Why not specify the encoding so that you know what bytes you are gonna get?

"Why is there a dependency on character encodings?"

Encoding (in this context) simply means the bytes that represent your string. Not the bytes of the string object. You wanted the bytes the string has been stored in -- this is where the question was asked naively. You wanted the bytes of string in a contiguous array that represent the string, and not all of the other binary data that a string object may contain.

Which means how a string is stored is irrelevant. You want a string "Encoded" into bytes in a byte array.

I like Tom Bloget's answer because he took you towards the 'bytes of the string object' direction. It's implementation dependent though, and because he's peeking at internals it might be difficult to reconstitute a copy of the string.

Mehrdad's response is wrong because it is misleading at the conceptual level. You still have a list of bytes, encoded. His particular solution allows for unpaired surrogates to be preserved -- this is implementation dependent. His particular solution would not produce the string's bytes accurately if GetBytes returned the string in UTF-8 by default.

I've changed my mind about this (Mehrdad's solution) -- this isn't getting the bytes of the string; rather it is getting the bytes of the character array that was created from the string. Regardless of encoding, the char datatype in c# is a fixed size. This allows a consistent length byte array to be produced, and it allows the character array to be reproduced based on the size of the byte array. So if the encoding were UTF-8, but each char was 6 bytes to accommodate the largest utf8 value, it would still work. So indeed -- encoding of the character does not matter.

But a conversion was used -- each character was placed into a fixed size box (c#'s character type). However what that representation is does not matter, which is technically the answer to the OP. So -- if you are going to convert anyway... Why not 'encode'?

BinaryFormatter bf = new BinaryFormatter();
byte[] bytes;
MemoryStream ms = new MemoryStream();

string orig = "喂 Hello 谢谢 Thank You";
bf.Serialize(ms, orig);
ms.Seek(0, 0);
bytes = ms.ToArray();

MessageBox.Show("Original bytes Length: " + bytes.Length.ToString());

MessageBox.Show("Original string Length: " + orig.Length.ToString());

for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo encrypt
for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo decrypt

BinaryFormatter bfx = new BinaryFormatter();
MemoryStream msx = new MemoryStream();            
msx.Write(bytes, 0, bytes.Length);
msx.Seek(0, 0);
string sx = (string)bfx.Deserialize(msx);

MessageBox.Show("Still intact :" + sx);

MessageBox.Show("Deserialize string Length(still intact): " 
    + sx.Length.ToString());

BinaryFormatter bfy = new BinaryFormatter();
MemoryStream msy = new MemoryStream();
bfy.Serialize(msy, sx);
msy.Seek(0, 0);
byte[] bytesy = msy.ToArray();

MessageBox.Show("Deserialize bytes Length(still intact): " 
   + bytesy.Length.ToString());

It depends on what you want the bytes FOR

This is because, as Tyler so aptly said , "Strings aren't pure data. They also have information ." In this case, the information is an encoding that was assumed when the string was created.

Assuming that you have binary data (rather than text) stored in a string

This is based off of OP's comment on his own question, and is the correct question if I understand OP's hints at the use-case.

Storing binary data in strings is probably the wrong approach because of the assumed encoding mentioned above! Whatever program or library stored that binary data in a string (instead of a byte[] array which would have been more appropriate) has already lost the battle before it has begun. If they are sending the bytes to you in a REST request/response or anything that must transmit strings, Base64 would be the right approach.

If you have a text string with an unknown encoding

Everybody else answered this incorrect question incorrectly.

If the string looks good as-is, just pick an encoding (preferably one starting with UTF), use the corresponding System.Text.Encoding.???.GetBytes() function, and tell whoever you give the bytes to which encoding you picked.


    string text = "string";
    byte[] array = System.Text.Encoding.UTF8.GetBytes(text);

The result is:

[0] = 115
[1] = 116
[2] = 114
[3] = 105
[4] = 110
[5] = 103

C # para convertir una string a una matriz de byte :

public static byte[] StrToByteArray(string str)
   System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
   return encoding.GetBytes(str);

Prueba esto, mucho menos código:

System.Text.Encoding.UTF8.GetBytes("TEST String");

If you really want a copy of the underlying bytes of a string, you can use a function like the one that follows. However, you shouldn't please read on to find out why.

        EntryPoint = "memcpy",
        CallingConvention = CallingConvention.Cdecl,
        SetLastError = false)]
private static extern unsafe void* UnsafeMemoryCopy(
    void* destination,
    void* source,
    uint count);

public static byte[] GetUnderlyingBytes(string source)
    var length = source.Length * sizeof(char);
    var result = new byte[length];
        fixed (char* firstSourceChar = source)
        fixed (byte* firstDestination = result)
            var firstSource = (byte*)firstSourceChar;

    return result;

This function will get you a copy of the bytes underlying your string, pretty quickly. You'll get those bytes in whatever way they are encoding on your system. This encoding is almost certainly UTF-16LE but that is an implementation detail you shouldn't have to care about.

It would be safer, simpler and more reliable to just call,


In all likelihood this will give the same result, is easier to type, and the bytes will always round-trip with a call to


You can use the following code for conversion between string and byte array.

string s = "Hello World";

// String to Byte[]

byte[] byte1 = System.Text.Encoding.Default.GetBytes(s);

// OR

byte[] byte2 = System.Text.ASCIIEncoding.Default.GetBytes(s);

// Byte[] to string

string str = System.Text.Encoding.UTF8.GetString(byte1);

Esta es una pregunta popular. Es importante comprender lo que pregunta el autor de la pregunta, y que es diferente de lo que probablemente sea la necesidad más común. Para desalentar el mal uso del código donde no es necesario, primero he respondido el primero.

Necesidad común

Cada cadena tiene un conjunto de caracteres y codificación. Cuando convierte un objeto System.String en una matriz de System.Byte , todavía tiene un juego de caracteres y una codificación. Para la mayoría de los usos, sabrá qué conjunto de caracteres y codificación necesita y .NET simplifica la "copia con conversión". Simplemente elija la clase de Encoding adecuada.

// using System.Text;
Encoding.UTF8.GetBytes(".NET String to byte array")

La conversión puede necesitar manejar casos donde el conjunto de caracteres objetivo o la codificación no admite un carácter que está en la fuente. Usted tiene algunas opciones: excepción, sustitución u omisión. La política predeterminada es sustituir un '?'.

// using System.Text;
var text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("You win €100")); 
                                                      // -> "You win ?100"

Claramente, las conversiones no son necesariamente sin pérdidas.

Nota: Para System.String el conjunto de caracteres fuente es Unicode.

Lo único confuso es que .NET usa el nombre de un conjunto de caracteres para el nombre de una codificación particular de ese juego de caracteres. Encoding.Unicode debe llamar Encoding.UTF16 .

Eso es todo para la mayoría de los usos. Si eso es lo que necesitas, deja de leer aquí. Vea el divertido joelonsoftware.com/articles/Unicode.html si no entiende qué es una codificación.

Necesidad específica

Ahora, el autor de la pregunta pregunta: "Cada cadena se almacena como una matriz de bytes, ¿verdad? ¿Por qué no puedo simplemente tener esos bytes?"

Él no quiere ninguna conversión.

De la especificación de C # :

El procesamiento de caracteres y cadenas en C # usa codificación Unicode. El tipo de carácter representa una unidad de código UTF-16, y el tipo de cadena representa una secuencia de unidades de código UTF-16.

Entonces, sabemos que si solicitamos la conversión nula (es decir, de UTF-16 a UTF-16), obtendremos el resultado deseado:

Encoding.Unicode.GetBytes(".NET String to byte array")

Pero para evitar la mención de codificaciones, debemos hacerlo de otra manera. Si un tipo de datos intermedio es aceptable, hay un atajo conceptual para esto:

".NET String to byte array".ToCharArray()

Eso no nos da el tipo de datos deseado, pero la respuesta de Mehrdad muestra cómo convertir esta matriz Char a una matriz Byte usando BlockCopy . Sin embargo, ¡esto copia la cadena dos veces! Y, de manera muy explícita, utiliza un código específico de codificación: el tipo de datos System.Char .

La única manera de llegar a los bytes reales en los que se almacena la cadena es usar un puntero. La instrucción fixed permite tomar la dirección de los valores. De la especificación de C #:

[Para] una expresión de tipo cadena, ... el inicializador calcula la dirección del primer carácter en la cadena.

Para hacerlo, el compilador escribe el código salteado sobre las otras partes del objeto de cadena con RuntimeHelpers.OffsetToStringData . Entonces, para obtener los bytes sin formato, solo cree un puntero a la cadena y copie el número de bytes necesarios.

// using System.Runtime.InteropServices
unsafe byte[] GetRawBytes(String s)
    if (s == null) return null;
    var codeunitCount = s.Length;
    /* We know that String is a sequence of UTF-16 codeunits 
       and such codeunits are 2 bytes */
    var byteCount = codeunitCount * 2; 
    var bytes = new byte[byteCount];
    fixed(void* pRaw = s)
        Marshal.Copy((IntPtr)pRaw, bytes, 0, byteCount);
    return bytes;

Como señaló @CodesInChaos, el resultado depende de la endianidad de la máquina. Pero al autor de la pregunta no le preocupa eso.

Bien, he leído todas las respuestas y se trata de usar codificación o una sobre serialización que quita a los sustitutos sin parear.

Es malo cuando la cadena, por ejemplo, proviene de SQL Server, donde se creó a partir de una matriz de bytes almacenada, por ejemplo, un hash de contraseña. Si eliminamos algo de él, almacenará un hash no válido, y si queremos almacenarlo en XML, queremos dejarlo intacto (porque el escritor XML descarta una excepción en cualquier sustituto sin aparear que encuentre).

Así que utilizo la codificación Base64 de matrices de bytes en tales casos, pero bueno, en Internet solo hay una solución para esto en C #, y tiene un error y es de una sola manera, así que he reparado el error y lo escribí de nuevo procedimiento. Aquí está, futuros googlers:

public static byte[] StringToBytes(string str)
    byte[] data = new byte[str.Length * 2];
    for (int i = 0; i < str.Length; ++i)
        char ch = str[i];
        data[i * 2] = (byte)(ch & 0xFF);
        data[i * 2 + 1] = (byte)((ch & 0xFF00) >> 8);

    return data;

public static string StringFromBytes(byte[] arr)
    char[] ch = new char[arr.Length / 2];
    for (int i = 0; i < ch.Length; ++i)
        ch[i] = (char)((int)arr[i * 2] + (((int)arr[i * 2 + 1]) << 8));
    return new String(ch);

With the advent of Span<T> released with C# 7.2, the canonical technique to capture the underlying memory representation of a string into a managed byte array is:

byte[] bytes = "rubbish_\u9999_string".AsSpan().AsBytes().ToArray();

Converting it back should be a non-starter because that means you are in fact interpreting the data somehow, but for the sake of completeness:

string s;
    fixed (char* f = &bytes.AsSpan().NonPortableCast<byte, char>().DangerousGetPinnableReference())
        s = new string(f);

The names NonPortableCast and DangerousGetPinnableReference should further the argument that you probably shouldn't be doing this.

Note that working with Span<T> requires installing the System.Memory NuGet package .

Regardless, the actual original question and follow-up comments imply that the underlying memory is not being "interpreted" (which I assume means is not modified or read beyond the need to write it as-is), indicating that some implementation of the Stream class should be used instead of reasoning about the data as strings at all.