Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-04-01
2
Medium Priority
?
1,740 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:James Atkin
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 5

Accepted Solution

by:
Dave Gould earned 2000 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:James Atkin
ID: 39968934
Perfect, thanks a lot :-)
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Utilizing an array to gracefully append to a list of EmailAddresses
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…

671 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