How to convert a normal string to an equivalent byte array in hex?

Viewed 312

My question is how can I convert,

string s = "Hello World";

into

byte b = {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64};

If there is a straightforward way in C# .NET Core then it will be very helpful.

2 Answers

The phrase "byte array in hex" makes no sense; bytes are bytes - they don't have any intrinsic format such as decimal, hex, octal: they're just values.

However, what you want is probably:

byte[] bytes = Encoding.UTF8.GetBytes(s);

to get the hex, you can then use tools to get a string again, for example:

string hex = BitConverter.ToString(bytes);

If you say you want an array of bytes for a given string, you have to specify in which way the byte array should represent the string. That's called encoding and the .NET framework has a built-in library (System.Text.Encoding) for handling string encoding operations.

For example, in order to get the string as ASCII representation, use this:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

Of course, ASCII is a very limited set of characters.

Just explore your option here:

Microsoft .NET documentation: Encoding Class

Related