How do we understand this addition of hexadecimal number with a decimal number in Julia?

Viewed 65

I recently obtained HDF5 data files which contain integer arrays that show up in hexadecimal format upon reading in julia (using HDF5 package). To get the numbers in the decimal format, I learned this trick from a colleague:

julia> a = 0x000038f9
0x000038f9

julia> b = a + 0
14585

I am trying to understand what Julia is doing here. Why/how the result of addition between a hexadecimal format number and decimal format number is a decimal format number. The official julia documentation doesn't seem to say much about this behavior. Is there a more transparent way to perform this conversion? Thank you.

1 Answers

This isn't about hexadecimal and decimal numbers, it's about signed and unsigned numbers. Int (and similar types like Int8, BigInt etc) can store positive and negative numbers, and are printed in decimal since that's the number system most people use. They are stored in binary just like numbers are in pretty much every programming language.

UInt (and friends) represent unsigned numbers (they must be greater than 0). They are printed in hexadecimal because one of the main places where they are used is for bitwise operations (logical masks, black magic involving reinterpreting Float64s etc). As such, it is useful to be able to see them in hexadecimal since that makes it much easier for people to see how the bits are layed out (since each digit of hexadecimal is just 4 bits).

In Julia Int+UInt=UInt, but Int+UInt32=Int(on 64 bit systems since Int is then 64 bit). As such, when you add a UInt32 to an Int, julia does the math (no base conversions needed, everything is binary internally), and displays the Int that results.

Related