Converting String to Byte Array in C#

Converting from string to byte

I think there is a little misunderstanding here. You actually already solved your problem. The computer does not care whether the number is decimal or hexadecimal or octadecimal or binary. These are just representations of a number. So only you care how it is to be displayed.

As DmitryBychenko already said:
0xBA is the same number as 186. It won't matter for your byte array if you want to store it there. It only matters for you as a user if you want to display it.

EDIT: you can test it by running this line of code:

Console.WriteLine((byteresult == Convert.ToInt32("BA", 16)).ToString());

Your code actually does what you want if I understood you correctly from your comments.

string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);

int test = uid_1 ^ uid_2 ;
string final = test.ToString("X");

// here you actually have achieved what you wanted.
byte byteresult = Byte.Parse(final , NumberStyles.HexNumber);

now you can use byteresult to store it in a byte[], and this:

byte[] MyByteArray = new byte[4];
MyByteArray [0] = byteresult;

should execute without problems.

How to Convert String to Byte Array?

You can try like this:

string str= "some string";
var bytes = System.Text.Encoding.UTF8.GetBytes(str);

And to decode:

var decodeString = System.Text.Encoding.UTF8.GetString(bytes);

Is it possible to convert a string to byte array in binary representation

You can do this much easier:

string s = "29";
var buffer = new byte[s.Length];
for (int i = 0; i < buffer.Length; i++) {
buffer[i] = (byte)(s[i] - '0');
}

Explanation:

  • We create a byte buffer with the same length as the input string since every character in the string is supposed to be a decimal digit.
  • In C#, a character is a numeric type. We subtract the character '0' from the character representing our digit to get its numeric value. We get this digit by using the String indexer which allows us to access single characters in a string.
  • The result is an integer that we cast to byte we can then insert into the buffer.

Console.WriteLine(buffer[0]) prints 2 because numbers are converted to a string in a decimal format for display. Everything the debugger, the console or a textbox displays is always a string the data has been converted to. This conversion is called formatting. Therefore, you do not see the result as binary. But believe me, it is stored in the bytes in the requested binary format.

You can use Convert.ToString and specify the desired numeric base as second parameter to see the result in binary.

foreach (byte b in buffer) {
Console.WriteLine($"{b} --> {Convert.ToString(b, toBase: 2).PadLeft(4, '0')}");
}

If you want to store it in this visual binary format, then you must store it in a string array

var stringBuffer = new string[s.Length];
for (int i = 0; i < stringBuffer.Length; i++) {
stringBuffer[i] = Convert.ToString(s[i] - '0', toBase: 2).PadLeft(4, '0');
}

Note that everything is stored in a binary format with 0s and 1s in a computer, but you never see these 0s and 1s directly. What you see is always an image on your screen. And this image was created from images of characters in a specific font. And these characters result from converting some data into a string, i.e., from formatting your data. The same data might look different on PCs using a different culture, but the underlying data is stored with the same pattern of 0s and 1s.

The difference between storing the numeric value of the digit as byte and storing this digit as character (possibly being an element of a string) is that a different encoding is used.

  • The byte stores it as a binary number equivalent to the decimal number. I.e., 9 (decimal) becomes 00001001 (binary).
  • The string or character stores the digit using the UTF-16 character table in .NET. This table is equivalent to the ASCII table for Latin letters without accents or umlauts, for digits and for the most common punctuation, except that it uses 16 bits per character instead of 7 bits (expanded to 8 when stored as byte). According to this table, the character '9' is represented by the binary 00111001 (decimal 57).

The string "1001" is stored in UTF-16 as

00000000 00110001  00000000 00110000  00000000 00110000  00000000 00110001

where 0 is encoded as 00000000 00110000 (decimal 48) and 1 is encoded as 00000000 00110001 (decimal 49). Also, additional data is stored for a string, as its length, a NUL character terminator and data related to its class nature.


Alternative ways to store the result would be to use an array of the BitArray Class or to use an array of array of bytes where each byte in the inner array would store one bit only, i.e., be either 0 or 1.

Converting String to Byte Array and vice versa

Probably, you are not looking for a text encoding but a serialization format. Text encodings are meant for text. The bytes you are processing are random bytes.

Does Base64 (Convert.ToBase64String) work for you?

You could also jam the bytes into chars (new string(myBytes.Select(b => (char)b).ToArray())). This will produce unreadable strings that are prone to being mangled by other systems. Likely not the right path.

Convert string to byte array c#

Assuming that you want to convert each string into a single byte (parse the string), here's a small program that should demonstrate how to do what you're looking for:

void Main()
{
string[] vals = new string[10];
// populate vals...
byte[] bytes = new byte[vals.Length];
int i = 0;
foreach (string s in vals)
{
bytes[i++] = byte.Parse(s);
}
}

Note that there's no error handling here for the case where the string doesn't parse properly into a byte; in that situation you'll get an exception from the byte.Parse method.



Related Topics



Leave a reply



Submit