user3187910
user3187910

Reputation: 21

Why is this bit function returning in reverse order?

I have a variable called "bitarray" which is an array of 'unsigned long' types. This is initially all zeros in binary format.

0000000000000000000000000000000

I use a mask to change this to a different number.

mask = 0x1FFFFFF; 
bitarray[n] = bitarray[n] ^ mask; 
printBinary(bitarray[n]);

Result:

0000000111111111111111111111111

Then I use bit shifting to check the value of each bit and print out what it's set to.

int i;
for(i=0; i<31; i++) {   
    if((val>>i) & 1)  {
        printf("1");
    } else {
        printf("0");
    }
}

The problem is this prints in the exact opposite order:

1111111111111111111111111000000

My goal is just to be able to check whether a bit is set.

Upvotes: 2

Views: 88

Answers (2)

chux
chux

Reputation: 153338

Switch for loop order

// for(i=0; i<31; i++) { 
for(i=31; i >= 0; i--) { 

Upvotes: 1

Andrew Brown
Andrew Brown

Reputation: 167

You want to print the most significant bit first. Maybe try something like this:

int i;
for(i=31; i>=0; i--) 
    printf("%d", (val>>i) & 1);
printf("\n");

Upvotes: 1

Related Questions