Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2028
  • Last Modified:

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

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
James Atkin
Asked:
James Atkin
1 Solution
 
Dave GouldOnsite SupportCommented:
> 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
 
James AtkinSenior Principle Software EngineerAuthor Commented:
Perfect, thanks a lot :-)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now