enaud
November 29, 2012, 4:20am
1
hi all,
this is my script:
#! /bin/sh
minutes=$( { i2cget -f -y 0 0x51 3; } 2>&1 )
minutes=${minutes:2}
hour=$( { i2cget -f -y 0 0x51 4; } 2>&1 )
hour=${hour:2}
day=$( { i2cget -f -y 0 0x51 5; } 2>&1 )
day=${day:2}
month=$( { i2cget -f -y 0 0x51 7; } 2>&1 )
month=${month:2}
year=$( { i2cget -f -y 0 0x51 8; } 2>&1 )
year=${year:2}
date -s 20$year$month$day-$hour:$minutes
i want get data and time from a RealTimeClock plugged on i2c of my embedded board and after setdate with this value.
but with i2cget command i receive an hexdecimal value like 0x54 and with year=${year:2} i have year =54 but i need convert this number to decimal, but how?
I cant use bc because in my embedded board there isnt.
thanks
What is on your embedded board? Do you have dc? What shells do you have?
Try this awk code:
awk 'BEGIN {
h["0"]="0"; h["1"]="1"; h["2"]="2"; h["3"]="3"
h["4"]="4"; h["5"]="5"; h["6"]="6"; h["7"]="7"
h["8"]="8"; h["9"]="9"; h["A"]="10"; h["B"]="11"
h["C"]="12"; h["D"]="13"; h["E"]="14"; h["F"]="15"
}
{
l=length($0)
s=h[substr($0,l--,1)]
for(i=l;i>=1;i--) {
s=s+ h[substr($0,i,1)]*(16^++j)
}
print s
}'
This is the out I get with with an example:
$ year=54
$ year=$(echo $year| awk 'BEGIN {
h["0"]="0"; h["1"]="1"; h["2"]="2"; h["3"]="3"
h["4"]="4"; h["5"]="5"; h["6"]="6"; h["7"]="7"
h["8"]="8"; h["9"]="9"; h["A"]="10"; h["B"]="11"
h["C"]="12"; h["D"]="13"; h["E"]="14"; h["F"]="15"
}
{
l=length($0)
s=h[substr($0,l--,1)]
for(i=l;i>=1;i--) {
s=s+ h[substr($0,i,1)]*(16^++j)
}
print s
}')
$
$ echo $year
84
$
Yoda
December 1, 2012, 12:37pm
4
year=54
printf "%d\n" "0x"$( echo $year )
84
ctsgnb
December 1, 2012, 4:57pm
5
$ year=54
$ echo "obase=10;ibase=16;$year" | bc
84
RudiC
December 1, 2012, 5:20pm
6
For the (bash) shell enthusiast; works for quite lengthy hex numbers; might work on other shells too after slight modifications:
$ year=ABCD
$ Nr=0; base=1;for i in $(echo -n ${year^^}|od -An -td1|tac -s" "); do ((Nr+=($i>54?$i-55:$i-48)*base )); ((base*=16)); done; echo $Nr
43981
#!/bin/bash
typeset -i hx=0xabcd
echo $hx