Easiest way to convert between integer and hex


MATLAB provides dec2hex, hex2dec and other such functions to go between different number representations. After searching on the web and Julia documentation, I couldn’t easily get hits on these type of questions (other than implementing our own conversion functions). It seems like Julia 0.6 had a hex function to show the hex representation of integers, but this doesn’t seem to exist on 1.1.


The way to go from integer to hex seems to be

s = string(12345, base = 16)

The hex to Integer seems easier


Are there easier/quicker ways to do the decimal to hex conversion? If not, is there a way to request Julia developers to provide functionality similar to MATLAB?

(I could eventually just do this myself and create a local package, but since I’m new, I’m not yet familiar with the proper steps to write custom functions and make them available systemwide.)


See the parse function.

To be clear, the only problem here is that you think writing s = string(12345, base = 16) is too long? Then the solution is indeed to locally define hex(s) = string(s, base=16).

This doesn’t convert “hex to integer”. It converts one integer type to another, explicitly, a UInt8 (unsigned 8-bit integer) to the native integer type (likely Int64). 0x10 is just a way of writing UInt8(16) and julia shows UInt8 in hex by default. That is just a choice how to print things to the user and has nothing with what the object is.


Correct. :slight_smile:

Yeah, I don’t really need to change the object type. I just need quick ways of simply viewing a value in different number representations in an easy way. The Int(0x10) perfectly does this one way. hex(20) would be a nice way to view the binary/hex representation of that integer.

Thanks, I’ll proceed with this.

julia> h = UInt(1);

julia> 10h

julia> 1234 * 1234h

Your move, MATLAB.


The inverse of string(12345, base = 16) is parse(Int, "3039", base = 16).

The inverse of Int(0x10) is UInt(16).

The two are very different things. Perhaps converting it to UInt is sufficient as you’re just interested in the display and unsigned integers display their value in hexadecimal.


So, basically Unit(xx) is my built-in hex function :slight_smile:

Haha, sold!!
Btw, in my initial reference to MATLAB, my intent was never to say MATLAB was easier/better, it was along the lines of what is the easiest workflow to adopt in Julia for what I’d been doing.

I needed to have signed integers as two’s complement hexadecimal representation too so I modified this solution a bit to:

hex(s; pad=4) = s < 0 ? string(2^(4*pad) + s, base=16, pad=pad) :  string(s, base=16, pad=pad)

Using ternary operator and pad to form the required width.

julia> hex(23)

julia> hex(-23)

julia> hex(23, pad=2)

julia> hex(-23, pad=2)

Of course you should have pad greater than 2^ceil(log2(abs(s))/4).