Results 1 to 4 of 4
Hi ,
I need to part a string into seperate integers ....like "0x0-0xffffffff,0x20000" into 3 integers 0x0 and 0xfffffff and 0x20000.... i can't use any other high-level languages ..
Please ...
- 12-02-2010 #1Just Joined!
- Join Date
- Oct 2010
- Posts
- 7
How to convert string into an integre in shell scripting ..
Hi ,
I need to part a string into seperate integers ....like "0x0-0xffffffff,0x20000" into 3 integers 0x0 and 0xfffffff and 0x20000.... i can't use any other high-level languages ..
Please help me on this ...
- 12-02-2010 #2
These hexadecimal numbers aren't really integers in bash.
Anyway, you can split the values into an array:If you want to convert a hexadecimal value into normal integer run:Code:declare -a arr arr=(`echo "0x0-0xffffffff,0x20000" | tr ",-" " "`) for i in ${arr[@]}; do echo ${i} doneCode:declare -i int int=(`printf "%d" $hexnumber`)
Last edited by Manko10; 12-02-2010 at 02:24 PM.
Refining Linux Advent calendar: “24 Outstanding ZSH Gems”
- 12-09-2010 #3Just Joined!
- Join Date
- Oct 2010
- Posts
- 7
@manko -- thanks for the help .. i've got another problem.i tried it but couldn't find anything as of now .. i am using kornshell and declare wont work in ksh .. here is what i've written and the error ..
set -A arr
arr=$( `echo $val | tr "-" " " | tr "," " "` )
index=0
for i in $( `echo $val | tr "-" " " | tr "," " "` ); do
if [ $index = 0 ];then
start=$(printf "%d" (echo ${i}))
elif [ $index = 1 ];then
end=$(printf "%d" $(echo ${i}))
elif [ $index = 2 ];then
step=$(printf "%d" $(echo ${i}))
else
echo "something wrong"
fi
index=$(($index + 1))
done
output:
/string_division[6]: "0x0: not found.
./string_division[8]: "0x0: not found.
i guesss its not taking 0x0 as input .. please help me on this ..
- 12-09-2010 #4
I'm not an expert in kornshell, but why do you use command substitution in the for loop? You've saved the data into an array before. You should use that instead. The same for your printf. Why do you use echo there instead of the variable? also the subshells there are not necessary and make your shell interpreting the output as commands etc.
EDIT:
Just compiled ksh for the sake of testing. That's the code I posted above translated for kornshell:Not much has changed, just a few minor syntax tweaks.Code:#!/bin/ksh set -A arr arr=(`echo "0x0-0xffffffff,0x20000" | tr ",-" " "`) for i in ${arr[*]}; do echo ${i} doneLast edited by Manko10; 12-09-2010 at 12:47 PM.
Refining Linux Advent calendar: “24 Outstanding ZSH Gems”


Reply With Quote