[Jprogramming] A clever way to find the maximum possible integer
Marshall Lochbaum
mwlochbaum at gmail.com
Tue Mar 15 03:22:36 UTC 2016
I just stumbled across the following snippet. Platform independent,
constant time (for those with 2048-bit processors, naturally), and only
nine characters!
33 b.~ _1
9223372036854775807
The verb (33 b.), not often used in J, is the unsigned shift operator,
like C's (<<). When the left operand x is positive, it has the same
effect as multiplying y by (2^x). If x is negative and y is positive, it
is the same as division by (2^-x) followed by rounding down. However, if
x and y are both negative, then y is shifted as an unsigned integer: all
of its bits are moved right by (|x), and (|x) zeros are added on the
left.
If y is _1, then its two's complement representation is all ones.
Shifting right by one leaves a number represented by a zero and then all
ones--the largest possible positive integer.
If you want both the maximum and minimum integers:
MIN_INT =: <:- MAX_INT =: 33 b.~ _1
Marshall
More information about the Programming
mailing list