Created
          January 29, 2015 14:56 
        
      - 
      
- 
        Save julianwachholz/dfdccdeda578b905b087 to your computer and use it in GitHub Desktop. 
    Ever needed to convert integers to bytes and back in javascript?
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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