Skip to content

Instantly share code, notes, and snippets.

@julianwachholz
Created January 29, 2015 14:56
Show Gist options
  • Save julianwachholz/dfdccdeda578b905b087 to your computer and use it in GitHub Desktop.
Save julianwachholz/dfdccdeda578b905b087 to your computer and use it in GitHub Desktop.
Ever needed to convert integers to bytes and back in javascript?
INT_BYTES = 8 # but note that javascript only does 2^53
int2bytes = (x) ->
if x > Number.MAX_SAFE_INTEGER
throw new Error "Number is larger than Number.MAX_SAFE_INTEGER (2⁵³-1)!"
bytes = []
i = INT_BYTES
loop
bytes[--i] = x & 0xff
x = (x - bytes[i]) / 0x100
break if not i
bytes
bytes2int = (bytes) ->
x = 0
for byte, i in bytes
x += byte
if i < bytes.length - 1
x = x * 0x100
x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment