1

One of the few programming assignments I had due was dealing with bit level operators and I was hoping I did this correctly.

#include <stdio.h>

int main(void){
    int x;
    printf("Enter an x: ");
    scanf("%x", &x);
    printf("X = %d\n", x);
//  Any bit in x is 1
    x && printf("A bit in x is 1!\n");
//  Any bit in x is 0
    ~x && printf("A bit in x is 0!\n");
//  Least significant byte of x has a bit of 1
    (x & 0xFF) && printf("A bit in least significant byte of x is 1!\n");
//  Most significant byte of x has a bit of 0
    int most = (x & ~(0xFF<<(sizeof(int)-1<<3)));
    most && printf("A bit in the most significant byte of x is 0!\n");
    return 0;
}

The assignment restricted what we could use so there could be no loops or conditionals and many other restrictions. I get a bit confused with the bit level operators so I was just hoping if there are any errors I could fix it and learn why it was wrong. Thanks.

WorldDominator
  • 141
  • 1
  • 5
  • 18
  • 3
    What is the point in not being allowed to use `if` when `&&` does the same thing? –  Feb 09 '14 at 18:02
  • That operator was introduced in the chapter. I think it was more for using if with ==. Does it look okay though? – WorldDominator Feb 09 '14 at 18:03
  • Depending on the portability you want, you shouldn't hardcode that a byte has 8 bits (0xFF). – Juri Robl Feb 09 '14 at 18:26
  • Please do not solve the question transparently, nobody will understand the answers and comments anymore. I rolled back to the original. If you have substantial corrections not mentioned in the answers you can write your own answer to show the correct code. –  Feb 09 '14 at 21:17

1 Answers1

2

You shouldn't use signed integers for these operations, because some cases result in undefined / implementation-defined behaviour: Arithmetic bit-shift on a signed integer

int most = (x & ~(0xFF<<(sizeof(int)-1<<3)));

You should negate x, not the right hand side:

int most = (~x & (0xFF<<(sizeof(int)-1<<3)));
Community
  • 1
  • 1
  • I was thinking I did need unsigned. Thanks for pointing that out to me. Also, the ~x is correct and it seems to work correctly now that I also changed my printf to %u as well. I'll update the above for onlookers. Thank you. – WorldDominator Feb 09 '14 at 18:50