tags:

views:

61

answers:

2

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);
}
+10  A: 

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
R Samuel Klatchko
yes but the ones returing full binary, not just 1 or 0.
sepp2k
@sepp2k - thanks, I'm much better with remembering how the features work and not their correct name
R Samuel Klatchko
pm100
Can you use terminal's printf in a similar way?
When performing bit manipulations, prefer `unsigned int` to `int`. The `unsigned int` lets you play with all the bits and not have to deal with sign extensions.
Thomas Matthews
+1  A: 
  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.

+1 if I had more points.
"unsigned int"?