Detect number of bytes required for an arbitrary number in Scala -
i'm trying figure out simplest way write function detect amount of bytes required number in scala.
for instance number
0 should 0 bytes 1 should 1 byte 127 should 1 byte 128 should 2 bytes 32767 should 2 bytes 32768 should 3 bytes 8388607 should 3 bytes 8388608 should 4 bytes 2147483647 should 4 bytes 2147483648 should 5 bytes 549755813887 should 5 bytes 549755813888 should 6 bytes 9223372036854775807 should 8 bytes. -1 should 1 byte -127 should 1 bytes -128 should 2 bytes -32767 should 2 bytes -32768 should 3 bytes -8388607 should 3 bytes -8388608 should 4 bytes -2147483647 should 4 bytes -2147483648 should 5 bytes -549755813887 should 5 bytes -549755813888 should 6 bytes -9223372036854775807 should 8 bytes
is there way besides doing math figuring out number wrt 2^n?
after precisions in comments, guess algorithm negative numbers be: whatever answer opposite be; , long.minvalue
not acceptable input value.
therefore, suggest:
def bytes(x: long): int = { val posx = x.abs if (posx == 0l) 0 else (64 - java.lang.long.numberofleadingzeros(posx)) / 8 + 1 }
tests needed.
Comments
Post a Comment