How do you get the Two's complement for a int in C?
Say for example I had an int such as -254, how would I go about converting this to 100000010?
Is there any way to pull out the Two's complement value from the integer variable, as I know that in C, the ints are stored in Two's comp?
know that in C, the ints are stored in Two's comp
Not guaranteed, but in practice every computer uses two's complement.
Is there any way to pull out the Two's complement value from the integer variable
It is already in two's complement format, so it is unclear what you are asking. It would seem you are asking how to print a variable in binary format?
int data = -254;
const size_t BITS = 8*sizeof(data);
char bin_str[BITS+1];
for(unsigned int i=0; i<BITS; i++)
{
unsigned int mask = 1u << (BITS - 1 - i);
bin_str[i] = (data & mask) ? '1' : '0';
}
bin_str[BITS] = '\0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With