Convert Hex to Dec and back again



Published: 2019-11-17 09:37:04 +0000
Categories: BASH,

Language

BASH

Description

Hex gets used a lot, and it's more than possible to figure it out in your head - up to a point

This snippet contains 2 simple routes to convert between Hexidecimal and Decimal with a slightly modified version at the end which converts a hex string into ascii chars

Snippet

# If you don't mind piping to python
echo $HEX | python -c 'import sys; print(int(sys.stdin.read(), 16))'
echo $DEC | python -c 'import sys; print(hex(int(sys.stdin.read())).split("x")[-1])'

# Or, without using Python
printf "%d\n" 0x$HEX
printf "%x\n" $DEC
printf "%o\n" $DEC # For completeness - Octal

Usage Example

# Hex to dec
echo 0a0d | python -c 'import sys; print(int(sys.stdin.read(), 16))'
2573

# Dec to Hex
echo 65355 | python -c 'import sys; print(hex(int(sys.stdin.read())).split("x")[-1])'
ff4b

# Hex to dec
printf "%d\n" 0x0a0d
2573

# Dec to hex
printf "%x\n" 65355
ff4b

# Dec to Oct
printf "%o\n" 25
31

# Take a string of Hex, extract the pairs, convert them to decimal and then to an Ascii char
echo -n 48656c6c6f20576f726c64a | python3 -c 'import sys,re; p=re.findall("..",sys.stdin.read()); [sys.stdout.write(chr(int(x,16)))for x in p];print("")'
Hello World

# Again for completeness, the input for that was generated by converting Ascii to Hex
echo "Hello World" | python3 -c 'import sys; p=sys.stdin.read(); [sys.stdout.write(hex(ord(x)))for x in p]; print("")' | sed 's/0x//g'
48656c6c6f20576f726c64a

Keywords

hex, dec, oct, ascii, base, convert, bash, python,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion