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).

esispaned
  • 273
  • 4
  • 19
  • 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. – CodeCaster Jul 17 '15 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. – Chris Jul 17 '15 at 10:14
  • I know that not such thing, I like to represent only what I what. Sorry for misunderstood :) – esispaned Jul 17 '15 at 10:19
  • Then what is your question? See [Converting a string to byte-array without using an encoding (byte-by-byte)](http://stackoverflow.com/questions/472906/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?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa) to print that byte array as hexadecimal... – CodeCaster Jul 17 '15 at 10:23
  • possible duplicate of [Converting string to byte array in C#](http://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp), just that it requires another step - converting the byte array to its string representation. – user35443 Jul 17 '15 at 10:25

2 Answers2

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"

Liem Do
  • 875
  • 1
  • 7
  • 13
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.

BG100
  • 4,162
  • 2
  • 34
  • 58