iOS5 Xcode4.2 floating-point byte align error?

。_饼干妹妹 提交于 2019-12-02 19:07:23

问题


Look at this code:

this is struct definition file with 1byte struct packing (for socket networking)

#pragma pack(1)

typedef struct _TestStruct1 {

double d1;
double d2;

} TestStruct1;


typedef struct _TestStruct2 {

unsigned long v1;
unsigned short v2;
unsigned long v3;
unsigned long value;
TestStruct1 ts1;

} TestStruct2;

#pragma pack()

Ok. now see simple code below:

TestStruct2 wtf;
wtf.v1 = 0;
wtf.v2 = 0;
wtf.v3 = 0;
wtf.value = 4294967295;
wtf.ts1.d1 = 37.785834f;
wtf.ts1.d2 = 37.785834f;
char * cp = (char *)&wtf;
for (int i = 0; i < sizeof(TestStruct2); i++) NSLog(@"[%d] %d", i, (int)cp[i]);
NSLog(@"wtf.value: %lu", wtf.value);

result on iphone 5.0 simulator XCode 4.2:

[0] 0
[1] 0
[2] 0
[3] 0
[4] 0
[5] 0
[6] 0
[7] 0
[8] 0
[9] 0
[10] -1
[11] -1
[12] -1
[13] -1
[14] 0
[15] 0
[16] 0
[17] 64
[18] -106
[19] -28
[20] 66
[21] 64
[22] 0
[23] 0
[24] 0
[25] 64
[26] -106
[27] -28
[28] 66
[29] 64
wtf.value: 4294967295

there is no problem. but when it comes to real device (iPhone4)...

[0] 0
[1] 0
[2] 0
[3] 0
[4] 0
[5] 0
[6] 0
[7] 0
[8] 0
[9] 0
[10] -1
[11] -1
[12] 0
[13] 0
[14] 0
[15] 64
[16] -106
[17] -28
[18] 66
[19] 64
[20] 0
[21] 0
[22] 0
[23] 64
[24] -106
[25] -28
[26] 66
[27] 64
[28] 88
[29] 84
wtf.value: 65535

oh my god what happen? I stored wtf.value with 4294967295, but on the device, it changes to 65535. this problem happens only on device, not on simulator.

This problem never happens before iOS5 XCode4.2.

How can I fix it? Please help me.


回答1:


I had a problem like this, involving floating-point miscalculations but in UI positioning code. I fixed it by adding:

-mno-thumb

to the "Other C Flags" options under Build Settings, for armv6 devices only ("Add Build Setting" > "Add Conditional Setting").

I don't pretend to understand exactly what's happening here, but by adding this build setting you're disabling the Thumb instruction set, which according to some (http://wanderingcoder.net/2010/07/19/ought-arm/) is not recommended for armv6 builds anyway. Thumb changes the way floating-point calculations work.




回答2:


And according to that same person (in reference to Craig's answer), that is, me, in that very same post, handling misaligned data on ARM is very bad (the simulator is x86). I can understand it for integers in network code (though I'd rather explicitly serialize), but there should be no reason to ever have misaligned floating-point numbers (here when you store the floating-point value it seems to be silently realigned to a 4-byte boundary and it overwrites part of wtf.value). You are not transmitting raw floating-point values over the network, right? Right?



来源:https://stackoverflow.com/questions/7763337/ios5-xcode4-2-floating-point-byte-align-error

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