Convert int to byte as HEX in C#
17,279
Solution 1
This format is called binary-coded decimal. For two-digit numbers, integer-divide by ten and multiply by sixteen, then add back the remainder of the division by ten:
int num = 45;
int bcdNum = 16*(num/10)+(num%10);
Solution 2
Another way to do this could be
c[1] = Convert.ToByte(num.ToString(), 16);
Author by
user1235288
Updated on June 05, 2022Comments
-
user1235288 about 2 years
I need to send a Hex string over the serial to a device, I do that now like this:
byte[] c = new byte[3]; c[0] = 0x57; c[1] = 0x30; ComPort.Write(c,0,c.Length );
Now I need to convert a value of int like 30 to
c[1] = 0x30
or a int value of 34 givesc[1] = 0x34
. I hope you see what I mean.So how can I mange this?
-
Waihon Yew almost 12 yearsWhat will you do if the value is
100
? -
user1235288 almost 12 yearsthe values are just between 30 and 39
-
Anders Arpi almost 12 yearsI don't understand the question. Could you try to elaborate a bit?
-
user1235288 almost 12 yearsIs there another way to send a HEX command by serial port I just found that I can do that over the 'byte[] c = new byte[3]' and afterwards with ComPort.Write(c,0,c.Length );
-
fdomig almost 12 yearsYou should rather change your input to e.g. 48 than 30 so you get 0x30 from it.
-
Sergey Kalinichenko almost 12 yearsWhat happened to byte
c[2]
? Is is intentional that it remains zero? -
user1235288 almost 12 yearsmissed c[2] it is also a value, however can I change the code to:(byte)(48) and this should give me 0x30???
-
Sergey Kalinichenko almost 12 years@user1235288 Yes,
(byte)48
is the same as its hex representation(byte)0x30
. -
user1235288 almost 12 yearsnice it does work that way! thx a lot!!!!
-
-
user1235288 almost 12 years@user1235288 Yes, (byte)48 is the same as its hex representation (byte)0x30.
-
Jeppe Stig Nielsen almost 12 yearsA struct
UInt4
ornibble
could have made this more intuitive. Then one could havenew nibble[6]
instead ofnew byte[3]
and then use0x4
together with0x5
instead of0x45
. -
Raulp over 9 yearswhat it will be for n digit number that can be contained by int?I mean any number to be expressed as 2 byte Hex numbers?
-
Jeremy Caney over 2 yearsRemember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?