merge: Add binary to decimal test file and convert function to es6 mo… · 96ADM/JavaScript@d5e309b · GitHub
Skip to content

Commit d5e309b

Browse files
authored
merge: Add binary to decimal test file and convert function to es6 model. (TheAlgorithms#806)
* Added Hex to Binary conversion * Add Binary to decimal test * Fix Style
1 parent 4ba2c32 commit d5e309b

4 files changed

Lines changed: 72 additions & 7 deletions

File tree

‎Conversions/BinaryToDecimal.js‎

Lines changed: 1 addition & 7 deletions

‎Conversions/HexToBinary.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const binLookup = (c) => {
2+
switch (c.toLowerCase()) {
3+
case '0': return '0000'
4+
case '1': return '0001'
5+
case '2': return '0010'
6+
case '3': return '0011'
7+
case '4': return '0100'
8+
case '5': return '0101'
9+
case '6': return '0110'
10+
case '7': return '0111'
11+
case '8': return '1000'
12+
case '9': return '1001'
13+
case 'a': return '1010'
14+
case 'b': return '1011'
15+
case 'c': return '1100'
16+
case 'd': return '1101'
17+
case 'e': return '1110'
18+
case 'f': return '1111'
19+
default: return ''
20+
}
21+
}
22+
const hexToBinary = (hexString) => {
23+
/*
24+
Function for convertung Hex to Binary
25+
26+
1. We convert every hexadecimal bit to 4 binary bits
27+
2. Conversion goes by searching in the lookup table
28+
29+
*/
30+
31+
let result = ''
32+
hexString = hexString.split('')
33+
hexString.forEach(c => { result += binLookup(c) })
34+
return result
35+
}
36+
37+
export default hexToBinary
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import binaryToDecimal from '../BinaryToDecimal'
2+
3+
describe('BinaryToDecimal', () => {
4+
it('expects to return correct decimal value', () => {
5+
expect(binaryToDecimal('1000')).toBe(8)
6+
})
7+
8+
it('expects to return correct hexadecimal value for more than one hex digit', () => {
9+
expect(binaryToDecimal('01101000')).toBe(104)
10+
})
11+
12+
it('expects to return correct hexadecimal value for padding-required binary', () => {
13+
expect(binaryToDecimal('1000101')).toBe(69)
14+
})
15+
})
Lines changed: 19 additions & 0 deletions

0 commit comments

Comments
 (0)