Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an int to hex and then pad it with 0's to get a fixed length String

I'm having some issues on trying to convert an int to hex then, padding it with 0s in order to get a 6 Characters String which represents the hex number.

So far, I tried the following:

intNumber := 12
hexNumber := strconv.FormatInt(intNumber, 16) //not working

And then I found out how to pad it with 0s, using %06d, number/string. It makes all the strings 6 characters long.

Here you can Find a Playground which I set up to make some tests.

How can I achieve this in a efficient way?

For any Clarifications on the question, just leave a comment below. Thanks In advance.

like image 966
AndreaM16 Avatar asked Oct 27 '16 20:10

AndreaM16


People also ask

Does Atoi work on hex?

atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.

How do you convert int to hex in python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.

Which method converts an int value into its equivalent hexadecimal?

An integer can be converted to a hexadecimal by using the string. ToString() extension method.


1 Answers

import "fmt"

hex := fmt.Sprintf("%06x", num)

The x means hexadecimal, the 6 means 6 digits, the 0 means left-pad with zeros and the % starts the whole sequence.

like image 61
Roland Illig Avatar answered Oct 25 '22 21:10

Roland Illig