skip to content

In a JavaScript review, `(a << 24) | (b << 16) | (c << 8) | d` packs an IPv4 address: why do addresses from 128.0.0.0 up come out negative, and how do you fix it?

level: seniorimportance: nice to knowfreq 27%

answer

  1. the bits are right, the reading is wrong
  2. bit 31 is the sign
  3. which bitwise operator returns unsigned
  4. must be the last step
  5. a shift count wraps too

basics

~20 s

Shifts and OR return signed 32-bit integers, so when the first octet reaches 128 the top bit becomes the sign bit and the value reads as negative. Apply >>> 0 last to reinterpret those same bits as unsigned.

solid answer

~50 s

On numbers, every bitwise operator in JavaScript returns a signed 32-bit integer, except `>>>`. With `a` at 128 or more, `a << 24` sets bit 31, the sign bit, so `192.168.0.1` packs to `-1062731775`. The bits are right, but the number reads wrong: sorting, range checks, `toString(16)` and an unsigned database column all see a negative value. The fix is `>>> 0` as the last step. It converts through ToUint32, shifts by nothing and returns `3232235521`. It must stay last, because any later `&`, `|` or `<<` goes back to signed, so for these addresses `(ip & mask) === network` fails against an unsigned `network` until you write `(ip & mask) >>> 0`. Extraction has the same trap: for that address `ip >> 24` gives `-64`, where `ip >>> 24` gives `192`. I would also validate each octet, because `256 << 24` wraps to `0` without complaint.

code

javascript · 10 lines
javascript
const pack = (a, b, c, d) =>
  ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;

const ip = pack(192, 168, 0, 1);
const network = pack(192, 168, 0, 0);
const mask = (-1 << 8) >>> 0; // a /24

console.log((ip & mask) === network);         // false
console.log(((ip & mask) >>> 0) === network); // true
console.log(ip >> 24, ip >>> 24);             // -64 192

go deeper

for a junior

Know that JavaScript's bitwise operators give signed 32-bit results, that >>> is the one giving an unsigned result, and that -1 >>> 0 is 4294967295. That is enough to recognise the symptom.

for a middle

Explain how bit 31 acts as a sign in two's complement, how >>> 0 reinterprets the same bits through ToUint32, and predict the difference between >> and >>> on a negative value.

for a senior

Reason from the symptom, failures only from 128.0.0.0 up, to the sign bit, and fix every comparison point rather than one line. Test the boundary addresses and validate octets, since the operators wrap in silence.

for a principal

If a codebase handles binary formats often, decide whether packing should live in one tested helper with typed-array or arithmetic internals, so product code never touches a raw shift and its sign rules.

## Signed by default The operators `&`, `|`, `^`, `~`, `<<` and `>>` convert their number operands to 32-bit signed integers, and they return a 32-bit signed integer. In **two's complement**, bit 31 is the **sign bit**: when it is set, the value is negative. An IPv4 address needs all 32 bits, so its first octet lands on the sign bit from 128 upward. | Address | Packed with `\|` | After `>>> 0` | Hex of the signed value | |---|---|---|---| | `10.0.0.1` | `167772161` | `167772161` | `a000001` | | `127.255.255.255` | `2147483647` | `2147483647` | `7fffffff` | | `128.0.0.0` | `-2147483648` | `2147483648` | `-80000000` | | `192.168.0.1` | `-1062731775` | `3232235521` | `-3f57ffff` | | `255.255.255.255` | `-1` | `4294967295` | `-1` | The bit pattern is correct in every row. Only the numeric reading changes, so a rewrite of the shifts cannot help, and `Math.abs` gives a different wrong number: `1062731775` is not the address. ## What `>>> 0` does `>>>` is the **unsigned right shift**. It converts its left operand with **ToUint32**, which reads the low 32 bits as a number from 0 to 4294967295, shifts in zeros, and returns that unsigned reading. A shift count of `0` moves nothing, so all that `>>> 0` does is reinterpret the bits. A result of `4294967295` is a perfectly ordinary, exact JavaScript number. ```javascript const pack = (a, b, c, d) => ((a << 24) | (b << 16) | (c << 8) | d) >>> 0; console.log(pack(192, 168, 0, 1)); // 3232235521 console.log(pack(192, 168, 0, 1).toString(16)); // "c0a80001" ``` The difference from `>>` shows on any negative value. `-9 >> 2` copies the sign bit in and gives `-3`, while `-9 >>> 2` shifts in zeros and gives `1073741821`. ## Where the sign comes back Being unsigned is a property of the last operation, not of the variable. So the fix has to be reapplied after anything that returns to signed: 1. **Masking.** `ip & mask` is signed again, so for an address with the top bit set `(ip & mask) === network` is `false` against an unsigned `network`, and `((ip & mask) >>> 0) === network` is `true`. 2. **Combining.** `(ip >>> 0) | 0` gives `-1062731775`, because `|` converts back. 3. **Extracting.** `ip >> 24` gives `-64` for `192.168.0.1`. Use `ip >>> 24`, or `(ip >> 24) & 255`. ## How to find it - **Test the boundary.** Run `127.255.255.255` and `128.0.0.0` side by side, then `255.255.255.255`. Private ranges under `10.x` hide the bug, so test data often misses it. - **Look for the symptom.** Addresses sort out of order, with `192.x` before `10.x`. Range checks fail for the upper half of the address space. `toString(16)` prints a leading minus sign. - **Check the boundary with storage.** An unsigned column may reject a negative value, or a signed one may store it, so that a later comparison against an unsigned value misses. - **Print in hex.** A decimal like `-1062731775` means nothing at a glance, while `c0a80001` reads directly as `c0.a8.00.01`, which is `192.168.0.1`. ## Related traps in the same code - **Octets are not validated by the operators.** `256 << 24` wraps to `0`, and `1.2.3.300` packs to the same value as `1.2.3.44`. A string such as `'x'` silently becomes `0`. Validate each octet is an integer from 0 to 255 before packing. - **Shift counts wrap as well.** The count is taken modulo 32, so `1 << 32` is `1`, not `0`. A prefix mask written as `(-1 << (32 - prefix)) >>> 0` is correct for `/24` but gives `4294967295` for `/0`, so handle that prefix separately. - **A midpoint can overflow.** `(lo + hi) >>> 1` is safe only while the sum stays under 2^32. With `lo = 3e9` and `hi = 3e9 + 2` it gives `852516353`, while `Math.floor((lo + hi) / 2)` gives `3000000001`. ## When to step away from bitwise operators Plain arithmetic never goes negative here: `a * 2 ** 24 + ((b << 16) | (c << 8) | d)` gives the same value as the `>>> 0` form. It suits code where the packed value is mainly compared and stored, while the `>>> 0` form suits code that keeps masking. For anything wider than 32 bits, the bitwise operators on numbers are the wrong tool at any rate, since their high bits are discarded. Whichever form you pick, keep it in one small helper with tests at the boundary addresses, so the signedness rule lives in one place.

  • Why does a prefix mask written as `(-1 << (32 - prefix)) >>> 0` break at `/0`?
    JavaScript takes a shift count modulo 32, so `-1 << 32` is the same as `-1 << 0` and stays `-1`. After `>>> 0` that becomes `4294967295`, an all-ones mask, where `/0` needs `0`. Handle `prefix === 0` as its own case, or build the mask with arithmetic.
  • Is `(lo + hi) >>> 1` a safe midpoint in JavaScript?
    Only while `lo + hi` stays below 2^32. The sum itself is exact, but `>>>` then discards everything above bit 31. With `lo = 3e9` and `hi = 3e9 + 2` it gives `852516353`. For indices that stay small it is fine; for large values use `Math.floor((lo + hi) / 2)`.
  • How would you diagnose this bug if the only report is that some subnet lookups fail?
    Split the failing inputs by first octet. If everything at 128 and above fails while lower addresses pass, suspect the sign. Log the packed value and its `toString(16)`: a minus sign settles it. Then find comparisons mixing a raw `&` result with a value produced by `>>> 0`.

  • The packed bits are wrong, so the shifts need rewriting
  • Math.abs repairs the negative value into the real address
  • >>> 0 is a no-op because it shifts by zero
  • Once a value has been through >>> 0, a later & or | keeps it unsigned
  • ip >> 24 reliably extracts the first octet
  • Shifting a number by 32 in JavaScript clears it to zero