Skip to content

Instantly share code, notes, and snippets.

# xem/LICENSE.txt forked from 140bytes/LICENSE.txt Created Sep 26, 2012

Enhanced binary operations: left shift, right shift, and a bonus: bit extraction
 /** * This function performs a left bit shift without risk of making a nagative result * (Native << produces negative numbers if the result is 0x80000000 or higher, multiplication doesn't) * @param a: number (the number to be shifted) * @param b: shift (the number of "0"s to add at the end of the number in binary notation) * @return the number, shifted **/ function l(a,b){ return // Return a // the number * // multiplied by Math.pow(2,b) // 2 ^ b. } /** * This function performs a right bit shift without risk of making a nagative result * (Native >> produces negative numbers if the result is 0x80000000 or higher, division doesn't) * @param a: number (the number to be shifted) * @param b: shift (the number of bits to remove at the end of the number in binary notation) * @return the number, shifted **/ function r(a,b){ return // Return Math.floor( // the entire part of a // the number / // divided by Math.pow(2,b) // 2 ^ b ) } /** * This function extracts certain bits of a number * @param a: number (the number to extract bits from) * @param b: start (first bit to read, starting at bit 0) * @param c: length (number of bits to read) * @return a number representing the bits extracted **/ function b(a,b,c){ return // Return r(a,b) // the number right-shifted (to place the bit b at the beginning of the number) & // AND (logical) Math.pow(2,c) - 1 // a bit mask made of c "1"s (in binary), i.e. (2 ^ c - 1) }
 function l(a,b){return a*Math.pow(2,b)}function r(a,b){return Math.floor(a/Math.pow(2,b))}function b(a,b,c){return r(a,b)&Math.pow(2,c)-1}
 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2012 MAXIME EUZIERE Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.
 { "name": "binaryOperations", "description": "Enhanced binary operations: left shift, right shift, and a bonus: bit extraction.", "keywords": [ "left", "right", "shift", "binary", "extraction" ] }
 Binary
Expected value: ff00
Actual value:
Expected value: f
Actual value:
Expected value: 100001
Actual value:
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.