pedro santos pedro santos - 1 month ago 4x
C Question

Why can't I print the number in binary properly?

I want to print a number using the program below but it never prints it correctly and i can't find the problem, can you help me?

#include <stdio.h>

int main(){

int value=3;
int mask=0x80000000;
int byte=0;
int bit=0;

for(byte=0; byte<4; byte++){

for(bit=0; bit<8; bit++){


printf(" ");
return 0;


There are other problems with your code, but the main one is your if statement.

if (value & mask == 1)

There are two problems:

  1. == hash higher precedence than &, so this is parsed as if you'd written value & (mask == 1). But you want to do the masking first, then the comparison, so you have to write (value & mask) == 1.

  2. When you do the masking, you won't usually get 1. When the masked bit is set, you'll get a number with 1 in that bit, not the lowest bit. Instead of using == 1, use != 0 to see if the bit is set. You could also use (value & mask) == mask.

When you change that line to:

if ((value & mask) != 0)

it will generally work.

However, your code has implementation-defined behavior because you're doing bit operations on signed integer variables. On a 32-bit system, 0x80000000 overflows the maximum value of int, and doing shifts of signed numbers is implementation-defined. Change value and mask to unsigned int and everything should be fine.