tags:

views:

5827

answers:

7

In a UNIX shell script, what can I use to convert decimal numbers into hexadecimal? I thought od would do the trick, but it's not realizing I'm feeding it ASCII representations of numbers.

printf? Gross! Using it for now, but what else is available? :)

+6  A: 

Tried printf(1)?

printf "%x\n" 34
22

There are probably ways of doing that with builtin functions in all shells but it would be less portable. I've not checked the POSIX sh specs to see whether it has such capabilities.

Keltia
It worked in my shell. Thanks.
skiphoppy
@Ollivier, salut encore! (-:
Rob Wells
A: 

try

printf "%X\n" ${MY_NUMBER}

HTH

cheers,

Rob

Rob Wells
+3  A: 
echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc
Bill Karwin
I looked at both bc(1) and dc(1) and missed that one.
Keltia
Any way to turn it into a filter that'll take an arbitrary number of integers, all on one line?
skiphoppy
@skiphoppy: If you write: echo "obase=16; 12 34 56" | bc you get 1E240, just the same as if you wrote: echo "obase=16; 123456" | bc. So the way to deal with arbitrary numbers of integers all on one line is to put each number on its own line: tr ' ' '\015' <input | bc (map blanks to newlines).
Jonathan Leffler
+1  A: 

Which shell are you using? In zsh you can do this sort of thing:

% typeset -i 16 y
% print $(( [#8] x = 32, y = 32 ))
8#40
% print $x $y
8#40 16#20
% setopt c_bases
% print $y
0x20

(Example taken from documentation.)

I believe bash has similar capabilities.

Alastair
A: 

I use this:

$ echo $((0xfee10000))

pjhobbs
Wrong direction - he wants decimal to hex, not hex to decimal.
mskfisher
A: 

Sorry my fault, try this...

#!/bin/bash
:

declare -r HEX_DIGITS="0123456789ABCDEF"

dec_value=$1
hex_value=""

until [ $dec_value == 0 ]; do

    rem_value=$((dec_value % 16))
    dec_value=$((dec_value / 16))

    hex_digit=${HEX_DIGITS:$rem_value:1}

    hex_value="${hex_digit}${hex_value}"

done

echo -e "${hex_value}"

$ ./dtoh 1024

400

pjhobbs
A: 

watever as if i care

akash juneja
sooo mean..........very bad loser
akash juneja
pagaal kahin ka
akash juneja