Search code examples
cbit-manipulationtwos-complementdata-representation

Algorithm to write two's complement integer in memory portably


Say I have the following:

int32 a = ...; // value of variable irrelevant; can be negative
unsigned char *buf = malloc(4); /* assuming octet bytes, this is just big 
                          enough to hold an int32 */

Is there an efficient and portable algorithm to write the two's complement big-endian representation of a to the 4-byte buffer buf in a portable way? That is, regardless of how the machine we're running represents integers internally, how can I efficiently write the two's complement representation of a to the buffer?

This is a C question so you can rely on the C standard to determine if your answer meets the portability requirement.


Solution

  • Yes, you can certainly do it portably:

    int32_t a = ...;
    uint32_t b = a;
    unsigned char *buf = malloc(sizeof a);
    
    uint32_t mask = (1U << CHAR_BIT) - 1;  // one-byte mask
    
    for (int i = 0; i < sizeof a; i++)
    {
        int shift = CHAR_BIT * (sizeof a - i - 1); // downshift amount to put next
                                                   // byte in low bits
        buf[i] = (b >> shift) & mask;  // save current byte to buffer
    }
    

    At least, I think that's right. I'll make a quick test.