Skip to content

Instantly share code, notes, and snippets.

@geo-stanciu
Created October 30, 2019 14:36
Show Gist options
  • Save geo-stanciu/a7cb4b0333d49e3b3bd7ddc78f09507b to your computer and use it in GitHub Desktop.
Save geo-stanciu/a7cb4b0333d49e3b3bd7ddc78f09507b to your computer and use it in GitHub Desktop.
Represent 4 byte int in byte array in c and c#
unsigned long n = 12121212;
unsigned long len = 0;
char msg[5];
msg[0] = (n >> 24) & 0xFF;
msg[1] = (n >> 16) & 0xFF;
msg[2] = (n >> 8) & 0xFF;
msg[3] = n & 0xFF;
msg[4] = 0;
for (int i = 0; i < 4; i++)
{
len <<= 8;
len |= (unsigned char)msg[i];
}
if (n != len)
{
printf("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\n");
}
else
{
printf("ok\n");
}
/////////////////////////////
// or in c#
/////////////////////////////
int len = 12121212;
byte[] msg = new byte[4 + 1 + len];
int k = 0;
msg[k++] = (byte)((len >> 24) & 0xFF);
msg[k++] = (byte)((len >> 16) & 0xFF);
msg[k++] = (byte)((len >> 8) & 0xFF);
msg[k++] = (byte)(len & 0xFF);
int len2 = 0;
for (int i = 0; i < 4; i++)
{
len2 <<= 8;
len2 |= msg[i];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment