cbittwos-complementuint16

Two's Complement Representation of int16_t


I am attempting to display a string representation of an int16_t's Two's Complement. I find the two's complement by (uint16_t)~value + 1;

How would I add the 16 bits to a string?

char* getBits(const int16_t value) {

    uint16_t complement = (uint16_t)~value + 1;
    char bits = malloc(16*sizeof(char*))

    for (int i = 0; i < 16; i++) {
        bits[i] = // something
    }
    return bits;
}

Solution

  • Shift complement right i bits, and test whether the low-order bit is 0 or 1 and put the corresponding character in bits.

    bits[i] = (complement >> i) & 1 ? '1' : '0';
    

    Also, you need to allocate an extra character in your string for the null terminator. And bits needs to be a pointer, while the element size is sizeof(char), not sizeof(char*).

    char *bits = malloc(17*sizeof(char));
    bits[16] = 0;
    

    There's no need to use the formula (uint16_t)~value + 1. Converting a signed int to unsigned int automatically returns its twos complement value. So you can simply do:

    uint16_t complement = (uint16_t)value;