answersLogoWhite

0

/* note that neither of these functions have been tested, so there may be typos and the like */

/* if you're looking to return a real value: */
unsigned int complement(unsigned int value){
unsigned int returnvalue = 0;
while(value){

returnvalue <<= 1;
returnvalue += !(value & 1);
value >>= 1;

}
return returnvalue;

}

/* if you're looking for a string representing the binary number: */
char *complement(unsigned int value){
int numchars = 8 * sizeof(unsigned int);
int n;
char *returnvalue = malloc((numchars + 1) * sizeof(char));

for(n = 0; n < numchars; n++){
if(value & (1 << (numchars - 1 - n))){
returnvalue[n] = '1';

}else{
returnvalue[n] = '0';

}

}
returnvalue[numchars] = (char)NULL;

return returnvalue;

}

User Avatar

Wiki User

15y ago

Still curious? Ask our experts.

Chat with our AI personalities

DevinDevin
I've poured enough drinks to know that people don't always want advice—they just want to talk.
Chat with Devin
ProfessorProfessor
I will give you the most educated answer.
Chat with Professor
RossRoss
Every question is just a happy little opportunity.
Chat with Ross

Add your answer:

Earn +20 pts
Q: 2's complement of a binary number in c language?
Write your answer...
Submit
Still have questions?
magnify glass
imp