“Unpacking” in C

2019-08-11 11:29发布

问题:

I am working on rewriting a script from python to C. I'm relatively new to C.

I have a variable in PYTHON which contains this values:

x = [chr(113),chr(80),chr(191),chr(70)]

y = "".join(x)

This will return this value of y:

y = qP¿F           #this is string

Now what I do is unpack this variable, store it to variable z to get the results that I wanted. Like this:

z = struct.unpack("<f",y)
print z[0]  #unpack returns a tuple of size 1

The value that I get is:

x = 24488.2207

which for my case is correct.

I was wondering if there is a same function in C that I can use for this?

回答1:

There is no need for such a function; provided the endianness is already correct the compiler can handle that case itself either through pointer casting or through a union type.

uint8_t data[4] = {113, 80, 191, 70};

printf("%f\n", (double)(*(float*)data));

...

$ ./a.out 
24488.220703