C related, store a signed long int (32bit) as 4 octets?

Posted by Doori Bar on Stack Overflow See other posts from Stack Overflow or by Doori Bar
Published on 2010-04-16T10:27:00Z Indexed on 2010/04/16 10:33 UTC
Read the original article Hit count: 130

Filed under:

I managed to get a unsigned long int octets-representation (BE) by reading IPv4 methods, and I managed to read about how signed integers are using the MSB as the sign indicator, which makes 00 00 00 00 to be 0, while 7F FF FF FF is 2147483647.

But I can't manage how to do the same for signed long integers?

#include <stdio.h>
#include <string.h>

int main (void)
{
    unsigned long int intu32;
    unsigned char octets[4];

    intu32 = 255;

    octets[3] = (intu32) & 255;
    octets[2] = (intu32 >> 8) & 255;
    octets[1] = (intu32 >> 16) & 255;
    octets[0] = (intu32 >> 24) & 255;
    printf("(%d)(%d)(%d)(%d)\n", octets[0], octets[1], octets[2], octets[3]);

    intu32 = (octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3];
    printf("intu32:%lu\n", intu32);

    return 0;
}

Thanks in advance, Doori bar

© Stack Overflow or respective owner

Related posts about c