Find the answer to your Linux question:
Results 1 to 4 of 4
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    How to convert string into an integre in shell scripting ..

    Hi ,
    I need to part a string into seperate integers "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 ...

  2. #2
    These hexadecimal numbers aren't really integers in bash.
    Anyway, you can split the values into an array:
    declare -a arr
    arr=(`echo "0x0-0xffffffff,0x20000" | tr ",-" " "`)
    for i in ${arr[@]}; do
        echo ${i}
    If you want to convert a hexadecimal value into normal integer run:
    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

  3. #3


    @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 "," " "` )
    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}))
    echo "something wrong"
    index=$(($index + 1))

    /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 ..

  4. $spacer_open
  5. #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.

    Just compiled ksh for the sake of testing. That's the code I posted above translated for kornshell:
    set -A arr
    arr=(`echo "0x0-0xffffffff,0x20000" | tr ",-" " "`)
    for i in ${arr[*]}; do 
            echo ${i}
    Not much has changed, just a few minor syntax tweaks.
    Last edited by Manko10; 12-09-2010 at 12:47 PM.
    Refining Linux Advent calendar: 24 Outstanding ZSH Gems

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts