Two's Complement Representation of int16_t

1.4k views Asked by At

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;
}
2

There are 2 answers

3
Barmar On BEST ANSWER

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;
0
0___________ On

Your code has many issues and it wont even compile. You need to learn what is pointer and what is not. How to use malloc and where to sstore its result. The best way is to read a good C book.

#include <stdint.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

char* getBits(const int16_t value) 
{
    uint16_t complement = value;
    char *bits = malloc(sizeof(value) * CHAR_BIT + 1);
    char *wrk = bits;

    if(bits)
    {
        for (unsigned i = 1 << 15; i; i >>= 1) 
        {
            *wrk++ = (complement & i) ? '1' : '0';
        }
        *wrk++ = 0;
    }
    return bits;
}



int main(void)
{
    for(int i = 0; i > -15; i --)
    {
        char *bits;
        printf("%d - %s\n", i, (bits = getBits(i)));
        free(bits);
    }
}