26

This seems to be an easy problem but i can't figure out.

I need to convert this character < in byte(hex representation), but if i use

byte b = Convert.ToByte('<');

i get 60 (decimal representation) instead of 3c.

DropTheCode
  • 465
  • 1
  • 7
  • 14

5 Answers5

27

60 == 0x3C.

You already have your correct answer but you're looking at it in the wrong way.

0x is the hexadecimal prefix
3C is 3 x 16 + 12

H H
  • 263,252
  • 30
  • 330
  • 514
16

You could use the BitConverter.ToString method to convert a byte array to hexadecimal string:

string hex = BitConverter.ToString(new byte[] { Convert.ToByte('<') });

or simply:

string hex = Convert.ToByte('<').ToString("x2");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thank you but i need a byte, if after conversion i use byte[] b = ASCIIEncoding.ASCII.GetBytes(hex); i get a byte array with 51 and 67 values. I need 3c. – DropTheCode Sep 21 '12 at 09:26
  • If you need a byte then don't call `.ToString`, simply: `byte b = Convert.ToByte('<');`. Also the `GetBytes` method doesn't do what you think it does. It doesn't expect a hex string. It expects a simple string where each character is converted to a byte using the specified encoding - it has nothing to do with hex. You should do the following if you want to get the original byte array from a hex string: http://stackoverflow.com/a/311179/29407 – Darin Dimitrov Sep 21 '12 at 09:27
6
char ch2 = 'Z';
Console.Write("{0:X} ", Convert.ToUInt32(ch2));
cc4re
  • 4,821
  • 3
  • 20
  • 27
4

get 60 (decimal representation) instead of 3c.

No, you don't get any representation. You get a byte containing the value 60/3c in some internal representation. When you look at it, i.e., when you convert it to a string (explicitly with ToString() or implicitly), you get the decimal representation 60.

Thus, you have to make sure that you explicitly convert the byte to string, specifying the base you want. ToString("x"), for example will convert a number into a hexadecimal representation:

byte b = Convert.ToByte('<');  
String hex = b.ToString("x");
Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

You want to convert the numeric value to hex using ToString("x"):

string asHex = b.ToString("x");

However, be aware that you code to convert the "<" character to a byte will work for that particular character, but it won't work for non-ANSI characters (that won't fit in a byte).

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276