Sign in to follow this  

Convert a number to a byte array

Recommended Posts

Fromethius    100
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 Oh, btw, this is for C#. However, I know VB.NET, C and C++ as well if you only have the code for that. Or perhaps you could just explain the technique in the conversion.

Share this post

Link to post
Share on other sites
wodinoneeye    1689

If this is C/C++ you could create a STRUCT which is a UNION of an array of bytes (matching the number type size) and the type itself. You would then set the variable of that STRUCT type via its numeric element and then access all the bytes via the array.

Be aware though that the storage of the bytes of the numeric value may not be the order you think they are ..... (that Big-Endian vs Little-Endian stuff)

Share this post

Link to post
Share on other sites
Fromethius    100
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?

Share this post

Link to post
Share on other sites
NerdInHisShoe    130
This is how I would do it in C:

Suppose you had a long integer and wanted to store it in 4 bytes

long x=0x67452301;
unsigned char y[4];

y[0] = x & 0x000000ff; //y[0] is the least significant byte
y[1] = (x & 0x0000ff00) >> 8;
y[2] = (x & 0x00ff0000) >> 16;
y[3] = (x & 0xff000000) >> 24

Share this post

Link to post
Share on other sites
TheTroll    883
This should help you.

class Hex
List<string> hex_list;

public Hex(int value)
hex_list = new List<string>();

Byte[] byteArray = BitConverter.GetBytes(value);

foreach (byte in_value in byteArray)


private void AddHex(byte in_byte)
byte first_significant = (byte)(in_byte % 16);
byte second_significant = (byte)((in_byte - first_significant)/16);

string temp = "0x" + GetHexString(second_significant) + GetHexString(first_significant);


private string GetHexString(byte value)
case 1:
return "1";
case 2:
return "2";
case 3:
return "3";
case 4:
return "4";
case 5:
return "5";
case 6:
return "6";
case 7:
return "7";
case 8:
return "8";
case 9:
return "9";
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
return "0";


Hope that helps.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this