Skip to content

Instantly share code, notes, and snippets.

@SET001
Last active February 5, 2020 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SET001/399269bb66412916e09dece9fb411f63 to your computer and use it in GitHub Desktop.
Save SET001/399269bb66412916e09dece9fb411f63 to your computer and use it in GitHub Desktop.
truncate number to size in bytes
const bitwiseTruncator = length => number => number & (Math.pow(2, length)-1);
((length, cTestNumbers, cTestNumbersMaxSize=999999)=>{
const numbers = Array.from({length: cTestNumbers}).map(()=>Math.ceil(Math.random()*cTestNumbersMaxSize))
const truncatedNumbers = numbers.map(bitwiseTruncator(length))
numbers.map((number)=>console.log(`was: ${number.toString(2)}`))
truncatedNumbers.map((number)=>console.log(`now: ${number.toString(length).padStart(length, "0")}`))
})(3, 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment