forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHexToBinary.js
More file actions
Latest commit
41 lines (36 loc) · 853 Bytes
/
Copy pathHexToBinary.js
File metadata and controls
41 lines (36 loc) · 853 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
constbinLookup=(key)=>({
0: '0000',
1: '0001',
2: '0010',
3: '0011',
4: '0100',
5: '0101',
6: '0110',
7: '0111',
8: '1000',
9: '1001',
a: '1010',
b: '1011',
c: '1100',
d: '1101',
e: '1110',
f: '1111'
}[key.toLowerCase()])// select the binary number by valid hex key with the help javascript object
consthexToBinary=(hexString)=>{
if(typeofhexString!=='string'){
thrownewTypeError('Argument is not a string type')
}
if(/[^\da-f]/gi.test(hexString)){
thrownewError('Argument is not a valid HEX code!')
}
/*
Function for converting Hex to Binary
1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table
*/
returnhexString.replace(
/[0-9a-f]/gi,
lexeme=>binLookup(lexeme)
)
}
exportdefaulthexToBinary