Dec to Bin: raw (bitwise)
/** * Dec to Bin * with bitwise operations * * Eudes Serpa M. **/ const numberToConvert = 5; const numberOfBits = 32; // 32-bits binary const arrBitwise = [0]; // save the resulting bitwise for (let i=0; i<numberOfBits; i++) { let mask = 1; const bit = numberToConvert & (mask << i); // And bitwise with left shift if(bit === 0) { arrBitwise[i] = 0; } else { arrBitwise[i] = 1; } } const binary = arrBitwise.reverse().join(""); console.log(`This is the resulting binary: ${binary}`) console.log(`This is the verification ${parseInt(binary, 2)}`);
Explanation:
Line 2: We specify the number of bits that will make up the resulting binary.
Line 3: We define an array in which we are going to save the bit resulting from the bit-level operations. In the end, it will be our resulting binary (reversing it)
For: Used to "create" the binary of bits.
Mask: Indicates the number to which we shift at the bit level (a 1 to do the AND and obtain the bits in 1 of the number to convert).
bit: It is the resulting bit of performing the operation, for example:
numberOfBits = 3;
mask = 1;
for (i = 0 -> 31) { // 32-bits
// Explanation of the operation to obtain the bit in position i // ---- For i = 0; 1. mask << 0 = ...0001 (a 1 in decimal), since it does not do any shifting. 2. 3 & 1 /* At the bit level we have to 3 = ...0011 1 = ...0001, so when doing the AND operation at the bit level, we have to: 0011 &0001 ------ 0001 === 1 decimal */ // bit then takes the value resulting from the previous operations. This is: bit = 1; // The if is not meet, so it enters the else: arrBitwise[0] = 1; // ---- For i = 1; 1. mask << 1 = ...0010 (a 2 in decimal) 2. 3 & 2 /* At the bit level we have to 3 = ...0011 2 = ...0010, so when doing the AND operation at the bit level, we have to: 0011 &0010 ------- 0010 === 2 decimal */ // bit then takes the value resulting from the previous operations. This is: bit = 2; // The if is not meet, so it enters the else: arrBitwise[1] = 1; // ----- For i = 2; 1. mask << 2 = ...0100 (a 4 in decimal) 2. 3. 4 /* At the bit level we have to 3 = ...0011 4 = ...0100, so when doing the AND operation at the bit level, we have to: 0011 &0100 ------- 0000 === 0 decimal */ // bit then takes the value resulting from the previous operations. This is: bit = 0; // The if meet, so: arrBitwise[2] = 0;
}
And so, arrBitwise would then be: arrBitwise = [1, 1, 0, 0, ..., 0];
arrBitwise.reverse() // [0, ..., 0, 0, 1, 1]
with .join()
"0...0011"
Which represents 3 in binary.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift
binary = int.toString(2);.