[2005] Convert a number to a byte array
I noticed that packets are sent in an array of bytes.
For example:
{ 0xF7, 0x13, 0xFE }
How can I convert a number such as 396 to a byte array such as this?
Thanks
Code examples aren't necessary. I'd rather just have the algorithm/technique in the conversion explained to me.
Re: [2005] Convert a number to a byte array
The first thing that comes to mind is the BitConverter:
vb Code:
Dim myBytes() As Byte = BitConverter.GetBytes(396)
Re: [2005] Convert a number to a byte array
The output that gives me is 140, 1, 0, and 0. 140 is 3 digits and not two so it cannot fit in the two bit 0xYZ format, no? Or perhaps I need to convert 140 to hex first?
Re: [2005] Convert a number to a byte array
Quote:
Originally Posted by Fromethius
The output that gives me is 140, 1, 0, and 0. 140 is 3 digits and not two so it cannot fit in the two bit 0xYZ format, no? Or perhaps I need to convert 140 to hex first?
Why do you need them in hex? It will still be the same value, must a different "format".
Re: [2005] Convert a number to a byte array
140 is 140, the computer doesn't care if they are in hex or dec. The byte will hold anything up to 255. The only difference between seeing that as hex or dec is which one you would prefer to see it in. However, when you are looking at it, and saying that it has three characters, that it because you are looking at a string representation of the number. The number is one byte, nothing more.
Re: [2005] Convert a number to a byte array
If you still want them in hex (although the computer doesn't care either way), you can use the Hex function.