4

I understand

  11001110
& 10011000
= 10001000

but I want to test it myself

so I declare unsigned char and print it out, but it just gives me blank.

unsigned char result;
result= 11001110 & 10011000;

cout<<result;

Also tested with unsigned int, but it gives me 0, which is not what I expected

Alston
  • 119
  • 2
  • 7
  • 1
    Those are decimal numbers. – BoBTFish May 14 '13 at 16:04
  • You're currently defining decimal numbers. See [this question](http://stackoverflow.com/q/2611764/311966) for how to specify a binary literal – simonc May 14 '13 at 16:04
  • that's because those numbers are decimal, not binary read [this thread][1] about how to use binary in C++ [1]: http://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c – Sergi0 May 14 '13 at 16:05
  • Well, we *will* be getting binary literals soon. – chris May 14 '13 at 16:05
  • 1
    @Sergi0, actually [this](http://stackoverflow.com/questions/537303/binary-literals/538101#538101) thread and answer, as C++11 is already here – Lol4t0 May 14 '13 at 16:13

5 Answers5

3

11001110 and 10011000 aren't binary numbers (at least in the compiler's mind).

Binary 11001110 is 206, and 10011000 is 152, so you actually want (I think):

result = 206 & 152;

or use a std::bitset and then print result as a binary.

taocp
  • 23,276
  • 10
  • 49
  • 62
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

You might want to consider using hex for testing

int a = 0xCE;    // 11001110
int b = 0x98;    // 10011000

int result = a & b;

cout << hex << result << endl;

or write a function to convert result to binary.

gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
1

In c++ you have to use hex to express bits number. Because 11001110 is 0XCE and 10011000 is 0X98

unsigned char b1 = 0XCE;
unsigned char b2 = 0X98;
unsigned char b = b1 & B2;
diwatu
  • 5,641
  • 5
  • 38
  • 61
  • You don't have to use hex. Decimal and octal work fine as well. Hex is just nicer sometimes. – chris May 14 '13 at 16:13
  • in standard c++, no octal data type you can use. if you use decimal(i know you mean integer here), it is hard to understand its bytes. – diwatu May 14 '13 at 16:15
  • @Giswin C++ has octal literals, just like it has hexadecimal literals. – juanchopanza May 14 '13 at 16:28
0

11001110 in binary is NOT the same number in decimal.

Since c++ does not have a binary specifier (but has hex and octal), you need to use something like an online converter.

Get an online binary to decimal converter, convert 11001110 to decimal, 10011000 to decimal, do the & operation, Then convert the result from decimal back to binary.

Boyko Perfanov
  • 3,007
  • 18
  • 34
0

If you write 11001110, you'll get a decimal, not a binary number, like Luchian pointed out.

To get a binary, you have to write 0b11001110... The prefix 0b means in gcc, clang and tcc, you are using binary system.

I don't know, what the Visual C++ Compiler will do with this prefix.

Uroc327
  • 1,379
  • 2
  • 10
  • 28