开发者

Hex to bin after logical operations

I want:

111 || 100  ---> 111,  not 1
100 && 100  ---> 100,  not 1
101 && 010  ---> 000,  not 0

Broken code

#include <stdio.h>

main(void){
        string hexa = 0xff;
        strig hexa2 = 0xf1;

        // CONVERT TO INT??? cast
      开发者_如何学运维  int hexa3 = hexa || hexa2;
        int hexa4 = hexa && hexa2;

        puts(hexa3);
        puts(hexa4);
}


You want the bitwise operators (|, &) instead of the logical operators (||, &&):

110 | 011 --> 111
110 & 101 --> 100

As for your broken code, you also have incorrect types for hexa and hexb which should both be numeric types:

int hexa = 0xff;
int hexa2 = 0xf1;

Finally, to output an integer, you would use printf to format them:

printf("hexa3 = 0x%08x\n", heaxa3);   // display as 8 digit, 0 padded hex


  1. string is not the right data type here. There is a big difference between the number 0xff (which is 11111111 in binary) and the string "0xff." I'm assuming you want to deal with the former; parsing strings into integers is an entire topic of its own. One good data type for a sequence of 16 bits is unsigned int.
  2. There is a big difference between || and |. The former does a so-called "logical" or: it converts both operands to a boolean and then return true if at least one of the operands is true, and false otherwise. A operand is converted into false if it is 0, true otherwise. Thus, for your example, 0xff and 0xf1 are both converted to true, and true || true == true. This is why your code prints 1.

Side note: even for booleans, || and | are different, because of short-circuiting: when you have a || b, b is only evaluated if a is false. Both arguments are evaluated for a | b. This matters, i.e., when one of the two operands is a function call with side-effects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜