|
| 1 | +const pad = (num, padlen) => { |
| 2 | + var pad = new Array(1 + padlen).join(0) |
| 3 | + return (pad + num).slice(-pad.length) |
| 4 | +} |
| 5 | + |
| 6 | +const hexLookup = (bin) => { |
| 7 | + let binary = bin |
| 8 | + if (binary.length < 4) { |
| 9 | + binary = pad(binary, 4) |
| 10 | + } |
| 11 | + switch (binary) { |
| 12 | + case '0000': return '0' |
| 13 | + case '0001': return '1' |
| 14 | + case '0010': return '2' |
| 15 | + case '0011': return '3' |
| 16 | + case '0100': return '4' |
| 17 | + case '0101': return '5' |
| 18 | + case '0110': return '6' |
| 19 | + case '0111': return '7' |
| 20 | + case '1000': return '8' |
| 21 | + case '1001': return '9' |
| 22 | + case '1010': return 'A' |
| 23 | + case '1011': return 'B' |
| 24 | + case '1100': return 'C' |
| 25 | + case '1101': return 'D' |
| 26 | + case '1110': return 'E' |
| 27 | + case '1111': return 'F' |
| 28 | + } |
| 29 | +} |
| 30 | +const binaryToHex = (binaryString) => { |
| 31 | + /* |
| 32 | + Function for convertung Binary to Hex |
| 33 | +
|
| 34 | + 1. The conversion will start from Least Significant Digit (LSB) to the Most Significant Bit (MSB). |
| 35 | + 2. We divide the bits into sections of 4-bits starting from LSB to MSB. |
| 36 | + 3. If the MSB get less than 4 bits, then we pad 0s to the front of it. |
| 37 | +
|
| 38 | + For Example: |
| 39 | + Binary String = '1001101' |
| 40 | +
|
| 41 | + 1. Divide it to 2 parts => ['100', '1101'] |
| 42 | + 2. Pad 0s the MSB so it'll be => ['0100', '1101'] |
| 43 | + 3. Use the lookup table and merge them, therefore the result is 4D. |
| 44 | +
|
| 45 | + */ |
| 46 | + |
| 47 | + let result = '' |
| 48 | + binaryString = binaryString.split('') |
| 49 | + for (let i = binaryString.length - 1; i >= 0; i = i - 4) { |
| 50 | + if (i >= 3) { |
| 51 | + result += hexLookup(binaryString.slice(i - 3, i + 1).join('')) |
| 52 | + } else { |
| 53 | + result += hexLookup(binaryString.slice(0, i + 1).join('')) |
| 54 | + } |
| 55 | + } |
| 56 | + return result.split('').reverse().join('') |
| 57 | +} |
| 58 | + |
| 59 | +export default binaryToHex |
0 commit comments