Solved

How do I convert an integer to hex and assign to a string in bash

Posted on 2014-04-01
2
1,311 Views
Last Modified: 2014-04-01
Hi all,

I am developing a bash script and I need to convert an integer number into a fixed format hex string.

for example, 255 would need to be stored as "00FF" and assigned to a variable

How do I do this (I am new to bash!)

Thanks,

James
0
Comment
Question by:jatkin
2 Comments
 
LVL 5

Accepted Solution

by:
Dave Gould earned 500 total points
ID: 39968900
> hexnum=`printf "%04x\n" 255`
> echo $hexnum
   00ff

The above example assigns the hex value for 255 to the variable "hexnum" with a fixed integer length of 4.
255 can be replaces with a variable that would make it more interesting for a script.

ie
>  i=254
> hexnum=`printf "%04x\n" $i`
> echo $hexnum
00fe
0
 
LVL 4

Author Closing Comment

by:jatkin
ID: 39968934
Perfect, thanks a lot :-)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question