Dang Khoa
Dang Khoa

Reputation: 5823

Is there a C union functionality in MATLAB?

I have some data that is being stored as an Nx32 logical array. Each row represents one word of UDP data that I'm sending. I'm storing it as a logical array because I could access any word, part of a word, or even across word boundaries. (I.e., I might store a uint32 as [array(1, 17:32) array(2, 1:16)]. Currently I find the data the user wants based on input word position, LSB, and MSB.

The functionality I'm writing into the classes to read to/write from places in the data essentially require that I convert any given MATLAB numeric type or char into its binary form, then store the binary form into the logical array, or vice versa. Basically there's a lot of num2hex and other conversions. (Actually, I tried to convert a float to binary using, say, dec2bin(hex2dec(num2hex(pi))) but the output is incorrect!).

In C, a union could easily cast between data types. I could write an int and read it out as a float directly. Is this functionality possible in MATLAB? I do have access to all the toolboxes if that helps.

Upvotes: 1

Views: 1420

Answers (2)

Navan
Navan

Reputation: 4477

Using dec2bin(hex2dec(num2hex(pi))) is not precise, because floating point numbers have large gaps for large numbers and cannot precisely represent integers. One workaround is to split the 64 bit hex string into two 32 bit strings. For example,

hexpi = num2hex(pi)
firstbin = dec2bin(hex2dec(hexpi(1:8)));
secondbin = dec2bin(hex2dec(hexpi(9:16)));

% reconstruct
firsthex = dec2hex(bin2dec(firstbin));
secondhex = dec2hex(bin2dec(secondbin));
hexpi_reconstructed = [firsthex secondhex]
pi_reconstructed = hex2num(hexpi_reconstructed)

That code should reproduce the same hexadecimal bits.

Upvotes: 2

horchler
horchler

Reputation: 18484

I not familiar with anything that directly matches with the concept of a union in Matlab, but but it's possible to obtain the same results (using more memory). I believe that you're looking for typecast, e.g.

x = uint32([1 2 3]);
y = typecast(x,'single')

If you need to change the order of the significant bit, use swapbytes.

EDIT: If you want to handle logicals, then you're going to have to use a binary string as a intermediate step. I think that dec2bin should be fine (no need to go to hexadecimal as far as I can see) and maybe your issue is that you're not providing the optional second argument that indicates how many bits to write?

x = dec2bin(22,32)

you can convert to logical and flip the bytes with

y = x=='1';
y = fliplr(y);

You could also possibly look into using Java from within Matlab, e.g., this for for doubles:

x = java.lang.Double.doubleToLongBits(22);
y = java.lang.Long.toBinaryString(x)

Upvotes: 4

Related Questions