Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added Hex to Binary conversion #805

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
raklaptudirm merged 8 commits into TheAlgorithms:master from ddhira123:master
Oct 24, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Conversions/HexToBinary.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const binLookup = (c) => {
switch (c.toLowerCase()) {
case '0': return '0000'
case '1': return '0001'
case '2': return '0010'
case '3': return '0011'
case '4': return '0100'
case '5': return '0101'
case '6': return '0110'
case '7': return '0111'
case '8': return '1000'
case '9': return '1001'
case 'a': return '1010'
case 'b': return '1011'
case 'c': return '1100'
case 'd': return '1101'
case 'e': return '1110'
case 'f': return '1111'
default: return ''
}
}
const hexToBinary = (hexString) => {
/*
Function for convertung Hex to Binary

1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table

*/

let result = ''
hexString = hexString.split('')
hexString.forEach(c => { result += binLookup(c) })
return result
}

export default hexToBinary
19 changes: 19 additions & 0 deletions Conversions/test/HexToBinary.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import hexToBinary from '../HexToBinary'

describe('hexToBinary', () => {
it('expects to return correct hexadecimal value', () => {
expect(hexToBinary('8')).toBe('1000')
})

it('expects to return correct binary value for more than one hex digit', () => {
expect(hexToBinary('EA')).toBe('11101010')
})

it('expects to test its robustness as it should be case-insensitive', () => {
expect(hexToBinary('4d')).toBe('01001101')
})

it('expects to return correct hexadecimal value, matching (num).toString(2)', () => {
expect(hexToBinary('F')).toBe(parseInt('F', 16).toString(2))
})
})

AltStyle によって変換されたページ (->オリジナル) /