Skip to content

Instantly share code, notes, and snippets.

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 imagineLife/4d90d0b0eea8e4f29343049053fdff67 to your computer and use it in GitHub Desktop.
Save imagineLife/4d90d0b0eea8e4f29343049053fdff67 to your computer and use it in GitHub Desktop.
Binary & Bitwise Operators Exercises
// Implement a function that takes in an integer and prints out its two's complement value by following the algorithm described above. Hint: to invert the bits of a number you can use the "~" operator. For example ~25 will invert the bits of the integer 25.
function twosComplement(int){
console.log('int to string is ' + int.toString(2));
const binaryInt = int.toString(2);
// console.log(binaryInt.length)
let result = '';
for (var i = 0; i < binaryInt.length; i++){
if (binaryInt[i] === '1') {
result = result.concat('0');
} else {
result = result.concat('1')
}
}
console.log('result is ' + result)
console.log(result.slice(-2))
const endDigits = result.slice(-2)
if (endDigits === '00') {
return result.slice(0, result.length-2) + '01'
} else if (endDigits === '01') {
return result.slice(0, result.length-2) + '10'
} else {
return result.slice(0, result.length-2) + '11'
}
}
twosComplement(514)
--------------------------------------------------
// Write a function that takes an integer value and checks to see if it is even or odd using the big-wise AND operator. Hint: Think about what the value of the least-significant bit will be for even and odd numbers.
function evenOrOdd (num) {
const binNum = num.toString(2);
if (binNum.slice(-1) === '1'){
return 'odd';
}
return 'even'
}
evenOrOdd(13379239774)
--------------------------------------------------
Why would using bit-wise operations be potentially faster for checking whether a number is even or odds as opposed to using something like the modulo operator (for example randInt % 2)?
ans: because there is no equation to be performed. you just need to know if the last number in binary is 1 or 0
--------------------------------------------------
Write a function that takes in two integer values and prints out the resultant value when you AND the two input values and then also when you OR the two input values.
!!this is not correct. it needs to check each position in the digital numbers against each other and return correct
function andOr (intA, intB){
const lastDigitA = intA.toString(2).slice(-1);
const lastDigitB = intB.toString(2).slice(-1);
let resultStr = '';
// AND
if (lastDigitA === '1' && lastDigitB === '1'){
resultStr += 'AND: 1, ';
} else {
resultStr += 'AND: 0, ';
}
// OR
if(lastDigitA === '0' && lastDigitB === '0') {
resultStr += 'OR: 0';
} else {
resultStr += 'OR: 1';
}
return resultStr;
}
console.log(andOr(4, 6))
console.log(andOr(4, 5))
console.log(andOr(3, 4))
console.log(andOr(3, 5))
--------------------------------------------------
// Extend the previous function further by adding logic for the XOR operation when two integer values are input. Add a third parameter which denotes which type of operation to execute. Print out the resultant value for the associated operation type.
function logicalOperation (intA, intB, type) {
const lastDigitA = intA.toString(2).slice(-1);
const lastDigitB = intB.toString(2).slice(-1);
if (type === 'AND'){
if (lastDigitA === '1' && lastDigitB === '1'){
return 'AND: 1';
} else {
return 'AND: 0';
}
}
else if (type === 'OR'){
if(lastDigitA === '0' && lastDigitB === '0') {
return 'OR: 0';
} else {
return 'OR: 1';
}
}
else if (type === 'XOR') {
if(lastDigitA !== lastDigitB){
return 'XOR: 1';
} else {
return 'XOR: 0';
}
}
}
--------------------------------------------------
Write a function that takes in an integer value and prints out its complement value.
function complement(int){
console.log(~int)
}
complement(3) // => -4
What do you notice about the numbers which are output? What about if you give a large input value?
ans: for positive integers the output is the integer made negative minus 1.
for negative integers the output is the integer made positive minus 1.
formula => ~x = -(x + 1)
--------------------------------------------------
// Write a function which sets the third bit of a number.
function thirdBit (int){
const intBinary = int.toString(2)
console.log('int in binary = ' + intBinary);
console.log('4 in binary = ' + (4).toString(2))
//four has a 1 in the third bit so performing an OR with the input will ensure the third bit is set
const intOr4 = (int | 4);
console.log('int or 4 = ' + intOr4.toString(2));
return intOr4
}
--------------------------------------------------
// Write a function which toggles the third bit of a number.
function thirdBitToggle(int){
const intBinary = int.toString(2);
console.log('int in binary = ' + intBinary);
console.log('4 in binary = ' + (4).toString(2))
const intXor4 = (int ^ 4);
console.log('int Xor 4 = ' + intXor4.toString(2));
return (int ^ 4)
}
thirdBitToggle(5)
--------------------------------------------------
Write a function which clears (sets to zero) the third bit of a number.
function thirdBitClear(int){
return (int & (~4))
}
ex:
5 = 101
~4 = 011
----------
& = 001 (or 1)
--------------------------------------------------
Write a function which tells you whether the third bit of a number is set.
function isSet(int){
if ((int & 4) !== 0) {
// bit is set
return '3rd bit set'
} else {
// bit is not set
return '3rd bit not set'
}
}
isSet(8) // => 3rd bit not set
isSet(12) // => 3rd bit set
ex
8 = 1000
4 = 0100
----------
& = 0000
ex
12 = 1100
4 = 0100
----------
& = 0100
--------------------------------------------------
//SHIFT OPERATORS
// it started to get complicated then i realized there were bitwise operators built into JS :P
function shifter (intA, intB){
// left shift
const resultLeft = `Left Shift: ${(intA * (2**(intB)))}, `;
// right shift
let resultRight = `Right Shift: ${intA >> intB}, `;
let prefix = '';
let zeroFillPrefix = '';
// if(intA > 0){
// for (var i = 0; i < intB; i++){
// prefix += '0';
// zeroFillPrefix += '0';
// }
// }
// else if (intA < 0){
// for (var j = 0; j < intB; j++){
// prefix += '1';
// zeroFillPrefix += '0';
// }
// }
// const shiftRightEnd = (intA.toString(2).slice(0, -(intB)));
// const shiftedRight = prefix + shiftRightEnd;
// resultRight += `${parseInt(shiftedRight, 10)}, `;
// zero-fill right shift
let resultZeroFill = `Zero Fill Right Shift: ${intA >>> intB}`;
// const zeroShiftedRight = zeroFillPrefix + shiftRightEnd;
// console.log(-17 >> 5)
// resultZeroFill += `${parseInt(zeroShiftedRight, 10)}`
return resultLeft + resultRight + resultZeroFill
}
shifter(13, 3)
--------------------------------------------------
// Using Shift Operators
// Write a function which doubles an integer.
function doubler(int) {
return int << 1
}
doubler(200)
--------------------------------------------------
Write a function which quadruples an integer.
function quadrupler(int) {
return int << 2
}
quadrupler(2)
--------------------------------------------------
// Write a function which divides an integer by two, rounding down.
function divideBy2(int) {
return int >> 1
}
divideBy2(567)
--------------------------------------------------
// Write a function which calculates 2^n.
function twoN (n){
return (1 << n)
}
twoN(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment