Skip to content

Commit ce9de4a

Browse files
authored
Update BinaryToHex.js
This is really all you need
1 parent 71d3d44 commit ce9de4a

File tree

1 file changed

+2
-58
lines changed

1 file changed

+2
-58
lines changed

Conversions/BinaryToHex.js

Lines changed: 2 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,3 @@
1-
const pad = (num, padlen) => {
2-
const pad = new Array(1 + padlen).join(0)
3-
return (pad + num).slice(-pad.length)
1+
function binaryToHex(binary) {
2+
return parseInt(binary,2).toString(16)
43
}
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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy