long number = 12501;
unsigned char mask = 1 << 7; // create a mask 10000000
for (size_t i=0; i<(sizeof(long)*8); ++i){ // iteration for all bits of long type
if (mask & number){
putchar('1');
} else {
putchar('0');
}
number <<=1; // I shift the most significant bit after every comparison
}
Is it possible to do a binary conversion using a char mask? My current output is: 0110100000000000000000000000000000000000000000000000000000000000
Expected output: 0000000000000000000000000000000000000000000000000011000011010101
Here you have a correct version
void printbin(long number)
{
unsigned long mask = 1LU << (sizeof(unsigned long) * CHAR_BIT - 1); // create a mask 10000000
for (; mask; mask >>= 1){ // iteration for all bits of long type
putchar((number & mask) ? '1' : '0');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.