0

Curious why this works

public long flip(long n) {
    long finalResult = 0;
    for (int i = 0; i < 32; i++) {
        finalResult = finalResult | (1L << i);
    }
    return n ^ finalResult;
}

but this doesn't

public long flip(long n) {
    long finalResult = 0;
    for (int i = 0; i < 32; i++) {
        finalResult = finalResult | (1 << i);
    }
    return n ^ finalResult;
}

I know that finalResult '11111111111111111111111111111111' will be -1 (and maybe that causes an issue) but i'm still not sure why it causes issues when simply flipping bits in n.

noi.m
  • 3,070
  • 5
  • 34
  • 57
  • 2
    Note that as written, both functions will do the same thing -- flip the lower 32 bits of value, leaving the upper 32 bits unchanged. Maybe you meant to write `i < 64` in the loop tests? In which case the first would flip all bits, and the second would just flip the lower 32 bits. – Chris Dodd Jan 10 '19 at 05:34
  • Java and C# follow the same rules for the [left shift operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/left-shift-operator) - "*If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. That is, the actual shift count is 0 to 31 bits.*" – Wai Ha Lee Jan 10 '19 at 05:35
  • @ChrisDodd - wouldn't the second flip the lower 32 bits *twice* and leave the input `n` unchanged? – Wai Ha Lee Jan 10 '19 at 05:37
  • @WaiHaLee: no, becuase the loop uses `|` not `^`... – Chris Dodd Jan 10 '19 at 05:39
  • Since [Java signed values are defined as two's-complement](https://stackoverflow.com/a/13422442/1270789), `return ~(n - 1);` is all that is needed? – Ken Y-N Jan 10 '19 at 05:41
  • @ChrisDodd i meant all 1s would be -1. Fixed question. – noi.m Jan 10 '19 at 16:46

0 Answers0