0

I like to convert String to HEX byte array.

From something like that "example" to byte[] exampleconv = {0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65} (Source: http://www.asciitohex.com/).

I search for example also on stackoverflow but most of example convert code from string to decimal byte array or similar. I didnt find any working! example to convert string to hex byte array (like exampleHEX shows above).

5
  • 2
    There is no such thing as a hexadecimal byte array. A byte is a byte. How you display a byte's value (e.g. binary, octal, decimal, hexadecimal) is up to you. Commented Jul 17, 2015 at 10:14
  • 1
    A byte is neither hex or decimal by its nature. You can display its value as either a decimal number of a hex number. Also when converting strings to bytes you need to be aware of what character encoding you want to use. For very basic english languages then ASCII will generally be fine but if you want characters from other languages or special characters (like emoji) then you'll want to use somethign like unicode. Commented Jul 17, 2015 at 10:14
  • I know that not such thing, I like to represent only what I what. Sorry for misunderstood :) Commented Jul 17, 2015 at 10:19
  • Then what is your question? See Converting a string to byte-array without using an encoding (byte-by-byte) to get a byte array from a string, see How do you convert Byte Array to Hexadecimal String, and vice versa? to print that byte array as hexadecimal... Commented Jul 17, 2015 at 10:23
  • possible duplicate of Converting string to byte array in C#, just that it requires another step - converting the byte array to its string representation. Commented Jul 17, 2015 at 10:25

2 Answers 2

2

Use Encoding.Default.GetBytes to get byte Array. Sample code:

byte[] ba = Encoding.Default.GetBytes("example");
// jsut to Display
var hexString = BitConverter.ToString(ba);
Console.WriteLine(hexString);

You will get "65-78-61-6D-70-6C-65"

Sign up to request clarification or add additional context in comments.

1 Comment

Depending on the string content, Encoding.Default may not be the way to go.
1

Byte arrays are stored in binary, regardless of how they are presented to the consumer.

You'll get more luck if you think about the format in which you read the array, rather than the type of numbers stored in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.