“Unpacking” in C

不想你离开。 提交于 2019-12-24 12:34:53

问题


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


来源:https://stackoverflow.com/questions/34937988/unpacking-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!