Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get two's complement of an int in C? [duplicate]

Tags:

c

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?

like image 445
Thahleel Abid Avatar asked Sep 03 '25 14:09

Thahleel Abid


1 Answers

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';
like image 92
Lundin Avatar answered Sep 05 '25 06:09

Lundin