Converting Decimals to Hex
Converting Hex to Binary is quite easy.
You just need paper and a pen.
But sometimes you have a sequence of decimal numbers, and you want to calculate their hexadecimal values.
bc command is your magic tool.
The bc command in Linux is a command-line utility that stands for “basic calculator”.
It provides a simple way to perform mathematical calculations within the terminal.
Here’s an example of how to use bc command for simple mathematical calculation:
$ echo "2 + 2" | bc
4We can use the bc command to convert decimal numbers to their hexadecimal equivalent.
bc uses two special variables for base conversion:
ibase (input base) sets the base of the numbers you provide,
and obase (output base) sets the base of the result.
By default, both are set to 10 (decimal).
For example, we can use bc to obtain the hexadecimal values for: [170 187 204 221 238 255]:
$ echo "obase=16; 170;187;204;221;238;255" | bc
AA
BB
CC
DD
EE
FFYou can play with the obase and ibase options.
One important note: always set ibase before obase, otherwise obase will be interpreted in the new base.
For instance you can convert hexadecimal to decimal like this:
$ echo "ibase=16; AA;BB;CC;DD;EE;FF" | bc
170
187
204
221
238
255If you want more fun, try this command by yourself:
$ echo "ibase=10;obase=2; 170;187;204;221;238;255" | bc