How to convert a number to an hexadecimal `bitstring`?

I can do

string(parse(Int, bitstring(x), base=2), base=16)

to convert bitstring(x) to an hexadecimal string, but is there another way, one which is simpler and doesn’t trim the leading zeros off of integers?

Why are you calling bitstring at all and then parsing it? Why not just call string(x, base=16) directly? If you want leading zeros, you can use the pad parameter.

(You can also use @printf or @sprintf from the Printf stdlib, e.g. @sprintf("%010x", x) is similar to string(x, base=16, pad=10). @printf also allows you to output directly to an io stream without converting to a string first.)

Because x is a floating point number and as far as I understand string takes only integer values.

Just do n = reinterpret(UInt64, x) first (assuming x is a Float64). Of course, you can then just do repr(n) or show(n) directly to see a hex representation.

(In general, you should rarely have to go through a string form to convert between two non-string types.)

3 Likes