Bitwise operations in C ++, how to actually use it?

I understand

11001110 & 10011000 = 10001000 

but I want to check it out myself.

so I declare an unsigned char and print it out, but it's just empty.

 unsigned char result; result= 11001110 & 10011000; cout<<result; 

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

+4
source share
5 answers

11001110 and 10011000 are not binary numbers (at least in the mind of the compiler).

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

 result = 206 & 152; 

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

+3
source

You might want to use 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 a binary file.

+3
source

In C ++, you should use hex to express the number of bits. Since 11001110 is 0XCE and 10011000 is 0X98

 unsigned char b1 = 0XCE; unsigned char b2 = 0X98; unsigned char b = b1 & B2; 
+1
source

11001110 in binary format is not the same number in decimal format.

Since C ++ does not have a binary qualifier (but it has hexadecimal and octal), you need to use something like an online converter.

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

0
source

If you write 11001110 , you will get a decimal number, not a binary number, as Lucian pointed out.

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

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

0
source

Source: https://habr.com/ru/post/1480755/


All Articles