r/Cplusplus • • 4d ago

Question Signed left shift causes overflow, and therefore undefined behavior

I was solving a question on Leetcode: Reversing Bits

The goal is simple, that we have been given an positive even number and we are supposed to reverse it's binary representation.

If we notice, it says "even" number - that implies the LSB is set to 0 and when we reverse the binary representation the 0 would move to MSB

I thought, it would be great to reverse it with just "bit manipulation" which is as folllows:

```cpp

n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1);
n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2);
n = ((n >> 4) & 0x0F0F0F0F) | ((n & 0x0F0F0F0F) << 4);
n = ((n >> 8) & 0x00FF00FF) | ((n & 0x00FF00FF) << 8);
n = (n >> 16)               | (n << 16);

```

Instead of reversing the number, we swap 2 bits, then 4 bits, then 8 bits and then 16 bits. The resultant sequence is exactly the reverse of the original binary representation.

Now, the incoming number is a signed int meaning it has range from:

```cpp

-2,147,483,648 to 2,147,483,647

-2^(31) to 2^(31) - 1

10000000 00000000 00000000 00000000 to 01111111 11111111 11111111 11111111

```

My perspective is that: Just shifting things around isn't really going to make it overflow, since it's a signed int - all that's gonna happen is the result will be interpreted in a wrong manner.

Example: Take the INT_MIN and << 1, what happens? Mathematically it should produce a smaller number that falls outside of the range of INT_MIN, but in computers the 1 is just discarded and we are left with a value of 0

Example: Take the INT_MAX and << 1, what happens? It turns into a negative number, because we are using signed int, does it over flow? not really.

I had initially used int for this and it produced wrong values because the reversed final value would be read as int, so i started casting int to uint and worked with it. Which internally should only work with positive numbers and correct binary representation and it worked.

Where it got weird was - I asked chatGPT to see if my logic is sound and it said that without the cast the number would just overflow in a signed int. From what I understand that's not really possible, because we are just shifting things around and even if we set the MSB to 1 ( for largest possible positive number ) it's just gonna get interpreted as a negative number.

Verdict: It won't overflow

But then it says that the representation is not an issue, it's c++ standard and due to that it may produce an undefined value - basically, in our first example it won't allow wrapping because mathematically it doesn't make sense. But it works!

At this point, i am 100% sure that it's wrong, it's just not possible to overflow the signed int through this algorithm, it makes sense to use uint because it would maintain proper representation internally and then finally when we cast it back to int - we would get the correct representation in signed format. It's only possible to overflow if we were working with decimal values.

I would say that even if the input was an odd number, still there wouldn't be any overflow just wrong representation!

TLDR: Don't sideline me for using AI, i just used it to summarize and verify my understanding. I think that it's wrong according to the current standards and undefined behavior or overflowing isn't really any issue. Just that the results will be wrong because it would be interpreted wrong.

The same would apply to even if the incoming number was negative or odd or completely positive (uint)

Thoughts?! What am I missing like would it really overflow?

9 Upvotes

14 comments sorted by

•

u/AutoModerator 4d ago

Thank you for your contribution to the C++ community!

As you're asking a question or seeking homework help, we would like to remind you of Rule 3 - Good Faith Help Requests & Homework.

  • When posting a question or homework help request, you must explain your good faith efforts to resolve the problem or complete the assignment on your own. Low-effort questions will be removed.
  • Members of this subreddit are happy to help give you a nudge in the right direction. However, we will not do your homework for you, make apps for you, etc.
  • Homework help posts must be flaired with Homework.

~ CPlusPlus Moderation Team


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/La-ze 4d ago

> Take the INT_MAX and << 1, what happens? It turns into a negative number, because we are using signed int, does it over flow?

It's undefined behavior, but I wouldn't be surprised if this raises the overflow flag. When talking about over/underflow, the textbook example is a positive or negative number wrapping around to the other side of the spectrum.

Sadly undefined behavior, is whatever goes, it's up to the compiler.

1

u/Any_Wait_7309 4d ago

got it, i think that makes it make sense for me. I kept getting confused because i wasn't getting any errors and it would just produce output.

For example: https://pz.run/5fAC4FNjLymJv ( programiz editor code example ), juts works fine for INT_MAX << 2 or << 4

1

u/La-ze 4d ago

It looks like programiz is using GCC 14.2.0 and with C++17, maybe GCC handles it differently than others, or programiz has some flags or hooks that alter behavior. With undefined, its difficult to say anything with confidence.

Undefined means the standard doesn't say what should happen.

1

u/Any_Wait_7309 3d ago edited 3d ago

I think, I finally understand it.

Overflow is defined differently for hardware and software.

For hardware it simply means that the bit is falling off (as you mentioned it), how the fell off bit is handled that's a different story.

For software it means that the interpreted number falls outside the valid representable numerical (decimal) range of the data type, it means at hardware level this particular data type doesn't have enough bits represent the value, which technically is undefined (as you mentioned).

The following is "hidden" steps explanation, doesn't mean it happens in this way: There may be a undefined error at software level because INT_MAX << 1 simply means 2 * INT_MAX which won't fit in the signed int range, but the compiler may handle << differently, and not throw an undefined error. Instead at hardware level it would just "overflow" the extra bits" and set the overflow flag (possibly) and then the compiler just interprets the result as signed int, this kind of behaves like modulo of range.

The same happens with unsigned int but it's more safe since there's no negative numbers!

The logic also works flawlessly for odd / even numbers! or infact even negative numbers. The goal of using unsigned int is to ensure that there's no magic fuckery with the MSB, it's just treated as a normal bit, saves us from a lot of pain! and when casting it back for sure it fits the range of normal int ( just interpreted as signed int instead of unsigned )

Damn, this stuff is def tricky lmao

1

u/La-ze 3d ago edited 3d ago

This might be easier to see in assembly. I ran this case in assembly on an online assembly compiler and got the overflow flag to be set to true.

Some debuggers can show the assembly registers & flags, such as the the overflow flag state.

You could bolt some in-line assembly if that's supported or in assembly use the x86 "jo" instruction to jump on overflow. You can use "godbolt.org" to translate a C program to assembly if you're curious and work your way from there.

I'm not sure I would say this is hardware vs software. At the end of the day, it's how the logic is defined. It can be programmed in hardware or software.

The solution is to not deal with undefined behavior at all.

1

u/Any_Wait_7309 3d ago

cool, thanks for staying with me through it!

The direction you provided is helpful!

1

u/I__Know__Stuff 3d ago

I think all you have to do to avoid undefined behavior and get a guaranteed correct result is to use a mask on the final line just like you did on the previous lines.
n = (n >> 16) | ((n & 0x0000ffff) << 16);

3

u/Any_Wait_7309 3d ago

.....and that fixed it.......without casting.....wow...

though it has to be:

 n = ((n >> 16) & 0x0000ffff )| ( (n & 0x0000ffff) << 16);

now, onto understanding it....

4

u/Discordbothost 3d ago

The mask on n >> 16 clears the bits added by sign extension. With input 65536, n is 0x80000000 before the last swap. Signed n >> 16 gives 0xffff8000. The mask leaves 0x00008000.

1

u/I__Know__Stuff 2d ago

Sorry about that. I thought about that mask and foolishly decided it wasn't needed.

1

u/no-sig-available 3d ago

My perspective is that: Just shifting things around isn't really going to make it overflow, since it's a signed int - all that's gonna happen is the result will be interpreted in a wrong manner.

Yes, and that is why the result is undefined - the language standard doesn't say what it should be.

Historically, hardware has used different ways to represent signed numbers, and C++ originally allowed three different ways - ones' complement, two's complement, and signed magnitude.

https://en.wikipedia.org/wiki/Signed_number_representations

So, instead of offering three different results, C and C++ just said that the result of some shifting of signed values was undefined.

Modern hardware supports only one of these, two's complement, but C++ hasn't cared to specify the result of signed shifts. Just use unsigned shifts, and it works.

0

u/BartvanIngenSchenau 3d ago

Your examples are flawed, because you are only considering logical shifts, but bit shifting on signed integers in C++ is defined such that it can also be implemented with an arithmetic shift.

Shifting a signed quantity such that the resulting value cannot be represented is deliberately left undefined, because logical shifts and arithmetic shifts give different results in those cases.

An arithmetic left-shift will always preserve the sign bit and an arithmetic right-shift will always 'shift in' the sign bit.

Unsigned shifts are defined such that only logical shifts can be used.

0

u/StaticCoder 2d ago

There is no possible overflow on the left operand of shifts (even if signed), at least in C++.

https://eel.is/c++draft/expr.shift