[Solved] Convert binary, octal, decimal and hexadecimal values between each other in BASH / Shell [duplicate]


Convert binary, octal, decimal and hexadecimal values between each other in BASH with bc and printf

  1. Some relevant Q&A:

Convert decimal to hexadecimal in BASH. Examples

echo "obase=16; 255" | bc
FF
echo "ibase=10; obase=16; 255" | bc
FF
echo "obase=16; ibase=10; 255" | bc
FF
printf "%x %08x %#x %#08x %X %08X %#X %#08X" {255,255,255,255,255,255,255,255}
ff 000000ff 0xff 0x0000ff FF 000000FF 0XFF 0X0000FF

Convert hexadecimal to decimal in BASH. Examples

echo "ibase=16; FF" | bc
255
echo "ibase=16; obase=10; FF" | bc # wrong
FF
echo "obase=10; ibase=16; FF" | bc
255
printf "%d " {0XFF,0X000000FF,0xff,0x000000ff}
255 255 255 255
echo $((16#FF))
255

Convert hexadecimal to binary in BASH. Examples

echo "ibase=16; obase=2; FF" | bc
11111111
echo "obase=2; ibase=16; FF" | bc
11111111

Convert binary to hexadecimal in BASH. Examples

echo "obase=16; ibase=2; 11111111" | bc
FF
echo "ibase=2; obase=16; 11111111" | bc # wrong
100110

Convert hexadecimal to octal in BASH. Examples

echo "ibase=16; obase=8; FF" | bc
377
echo "obase=8; ibase=16; FF" | bc
377
printf "%o " {0XFF,0X000000FF,0xff,0x000000ff}
377 377 377 377
printf "%#o " {0XFF,0X000000FF,0xff,0x000000ff}
0377 0377 0377 0377
printf "%08o " {0XFF,0X000000FF,0xff,0x000000ff}
00000377 00000377 00000377 00000377

Convert octal to hexadecimal in BASH. Examples

echo "obase=16; ibase=8; 377" | bc
FF
echo "ibase=8; obase=16; 377" | bc # wrong
143
printf "%x %08x %#x %#08x %X %08X %#X %#08X" {0377,0377,0377,0377,0377,0377,0377,0377}
ff 000000ff 0xff 0x0000ff FF 000000FF 0XFF 0X0000FF

solved Convert binary, octal, decimal and hexadecimal values between each other in BASH / Shell [duplicate]