简体   繁体   中英

How to convert a string to byte array

I have a string and want to convert it to a byte array of hex value using C#.
for eg, "Hello World!" to byte[] val=new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21};,

I see the following code in Converting string value to hex decimal

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
     // Get the integral value of the character.
     int value = Convert.ToInt32(letter);
     // Convert the decimal value to a hexadecimal value in string form.
     string hexOutput = String.Format("0x{0:X}", value);                
     Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}

I want this value into byte array but can't write like this

byte[] yy = new byte[values.Length];
yy[i] = Convert.ToByte(Convert.ToInt32(hexOutput));

I try this code referenced from How to convert a String to a Hex Byte Array? where I passed the hex value 48656C6C6F20576F726C6421 but I got the decimal value not hex.

public byte[] ToByteArray(String HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    }
    return bytes;
}

and I also try code from How can I convert a hex string to a byte array?

But once I used Convert.ToByte or byte.Parse , the value change to decimal value. How should I do?

Thanks in advance

I want to send 0x80 (ie, 128) to serial port but when I copy and paste the character equivalent to 128 to the variable 'input' and convert to byte, I got 63 (0x3F). So I think I need to send hex array. I think I got the wrong idea. Pls see screen shot.

在此输入图像描述

For now, I solve this to combine byte arrays.

string input = "Hello World!";
byte[] header = new byte[] { 2, 48, 128 };
byte[] body = Encoding.ASCII.GetBytes(input);

Hexadecimal has nothing to do with this, your desired result is nothing more nor less than an array of bytes containing the ASCII codes.

Try Encoding.ASCII.GetBytes(s)

There's something strange with your requirement:

I have a string and want to convert it to a byte array of hex value using C#.

An byte is just an 8-bit value. You can present it as decimal (eg 16) or hexidecimal (eg 0x10).

So, what do you realy want?

In case you are really wanting to get a string which contains the hex representation of an array of bytes, here's how you can do that:

public static string BytesAsString(byte[] bytes)
{
    string hex = BitConverter.ToString(bytes); // This puts "-" between each value.
    return hex.Replace("-","");                // So we remove "-" here.
}

It seems like you're mixing converting to array and displaying array data.

When you have array of bytes it's just array of bytes and you can represent it in any possible way binary, decimal, hexadecimal, octal, whatever… but that is only valid if you want to visually represent these.

Here is a code that manually converts string to byte array and then to array of strings in hex format.

string s1 = "Stack Overflow :)";
byte[] bytes = new byte[s1.Length];
for (int i = 0; i < s1.Length; i++)
{
      bytes[i] = Convert.ToByte(s1[i]);
}

List<string> hexStrings = new List<string>();

foreach (byte b in bytes)
{
     hexStrings.Add(Convert.ToInt32(b).ToString("X"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM