Port C++ union to Julia

question

#1

I am porting some complex C++ code to Julia. The one part that has me really perplexed is how to port the C++ concept of a union. If you aren’t familiar with union, its like a structure, but all of the members share the exact same memory space. So an array of two UInt32s and a Float64 are supposed to be in the same 8 bytes. The code I am looking at loads the array with a couple of Ints, does some bit shifting and then reads the resultant Float.

In Julia I have been doing the manipulation of the ints, getting the bit patterns, and concatenating them and parsing as a float. That doesn’t work. I guess I need to talk to someone that understands the internal representation of data in a union to help me figure out a way of replicating the results.

I fully admit this is straight up sorcery. No one should write an int array to a union and then read it as a float. However, it’s the code I have to port so… have pity on me. :slight_smile:


#2

You can store it as UInt64 and use i64 % UInt32 to get a UInt32 and reinterpret(Float64, i64) to get a Float64. Julia is type safe by default so it’s non-trivial to come up with a representation of C compatible union.


#3

I think I understand you, though I am not sure.

A = UInt32(1293080650)
B = UInt64(1074340347) << 32
C = A + B
reinterpret(Float64, C)

That should in theory be the same as what is happening in a union, right?


#4

Yes. There are multiple ways to shuffle bits around in a UInt64. What fits you the best depends on your application.


#5

I tested it out and it worked perfectly. In my own application there were some other, distracting, issues, but the code snippet I put above is a great simplification and general solution. Thanks for the help @yuyichao!