Sign Extension

  • A negative int that’s sign extended is padded with ones not zeroes.
  • Java sign extends when casting from int to long; this is especially significant because Java doesn’t have unsigned ints, so an int with a high first bit is considered negative. Specifically, this can be a problem when twiddling bits directly:
;; First bit is used to denote the sign, so the max value is (2^31)-1 instead of (2^32)-1
> (Integer/MAX_VALUE)
2147483647

;; and the min value is -(2^31).
> (Integer/MIN_VALUE)
-2147483648

> (Long/toBinaryString (Integer/MAX_VALUE))
"1111111111111111111111111111111"

> (Long/toBinaryString (Integer/MIN_VALUE))
"1111111111111111111111111111111110000000000000000000000000000000"

;; `2r` denotes a Clojure binary literal
> (long 2r1111111111111111111111111111111)
2147483647

;; This is incorrectly interpreted as a positive number
> (long 2r1111111111111111111111111111111110000000000000000000000000000000)
Execution error (IllegalArgumentException) at /eval13060 (form-init2730003737097781770.clj:229).
Value out of range for long: 18446744071562067968
Edit