When I give to a variable such value: e = 17|-15;
, I get -15 as an answer after compiling.I can't understand what arithmetic c++ uses. How does it perform a bit-wise OR operation on negative decimals?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
A bitwise or with a negative number works JUST like a bitwise or with a positive number. The bits in one number are ored with the bits in the other number. How your processor represents negative numbers is a different matter. Most use something called "two's complement", which is essentially "invert the number and add 1".
So, if we have, for simplicity, 8 bit numbers:
The operator
|
is a "bitwiseOR
" operator, meaning that every bit in the target is computed as theOR
-combination of the corresponding bits in the two operands. This means, that a bit in the result is1
if any of the two bits in the numbers at the same positions are1
, otherwise0
.Clearly, the result depends on the binary representation of the numbers which again depends on the platform.
Almost all platforms use the Two's complement, which can be thought as a circle of unsigned numbers, in which negative numbers are just in the opposite direction than positive numbers and "wrap around" the circle.
Unsigned integers:
Signed integers:
The calculation of your example is as follows.
you have to looks at how the bits work
Basically, if either number has a
1
in a particular spot, than the result will also have a1
as you can see, the result is the same as
-15
It's just doing the operation on the binary representations of your numbers. In your case, that appears to be two's complement.
As you can see, the bitwise
OR
of those two numbers is still-15
.In your comments above, you indicated that you tried this with the two's complement representations, but you must have done something wrong. Here's the step by step:
It does OR operations on negative numbers the same way it does so on positive numbers. The numbers are almost certainly represented in two's-complement form, which gives you these values:
As you can see, all the bits of 17 are already set in −15, so the result of combining them is again −15.