Lawkuy Tiu
Lawkuy Tiu

Reputation: 31

Hex Variables in C#

Part of my code snippet is found below:

Byte[] blockdata = new Byte[16];
blockdata[0] = 0x12;
blockdata[1] = 0x13;
blockdata[2] = 0x14;

Alright. The 12 in (0x12) is fixed. What if I want to use a variable for it? Example:

int m = 12;
blockdata[0] = 0xm;

In the above, m is supposed to be 12. How will I do that?

Help me please. Thanks.

Upvotes: 3

Views: 15902

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Just convert:

  • first to string
  • then from string treating it as a hexadecimal representation

like this

int m = 12;

blockdata[0] = Convert.ToByte(m.ToString(), 16);

Test:

 // 18 == 0x12
Console.Write(String.Format("{0} == 0x{0:x}"), blockdata[0]);

Upvotes: 2

lokusking
lokusking

Reputation: 7456

Another way to achieve your goal might be

int bInt = 12;
byte b = 0x1;
b = Convert.ToByte("0x" + bInt,16);

Upvotes: 2

Codor
Codor

Reputation: 17605

The expression 0x12 is a compile-time constant which cannot be changed at runtime. Hexadecimal 12 is the same value as 18 decimal, so you can just use

blockdata[0] = 18

to assign the desired value. There is no necessity to initialize variables of type Byte with constants using the hexadecimal format.

Upvotes: 1

Related Questions