开发者

Getting SIGILL in float to fixed conversion

开发者 https://www.devze.com 2022-12-26 01:09 出处:网络
I\'m receiving a SIGILL after running the following code. I can\'t really figure what\'s wrong with it.

I'm receiving a SIGILL after running the following code. I can't really figure what's wrong with it.

The target platform is ARM, and I'm trying to port a known library (in which this code is contained)

void convertFloatToFixed(float nX, float nY, unsigned int &nFixed) {
    short sx = (short) (nX * 32);
    short sy = (short) (nY * 32);

    unsigned short *ux = (unsigned short*) &sx;
    unsigned short *uy = (unsigned short*) &sy;

    nFixed = (*ux << 16) | *uy;
}

Any help on it would be greatly appreciated.

Tha开发者_运维百科nks in advance


Some ARM processors have hardware floating-point, and some don't, so it's possible that this function is being compiled for hardware floating-point but your platform lacks a floating-point unit, so the floating-point instructions cause the processor to report an illegal instruction. If this is the first floating-point computation in your test program, that's extremely likely to be the problem. Check your platform's documentation to find which -march option you need to pass to gcc, or look at the compilation options used by some program that already works.

This function does not have defined behaviour, and without an indication of what the desired behaviour is it's hard to suggest an improvement. Try something like this for a start:-

void convertFloatToFixed(float nX, float nY, unsigned int &nFixed) {
    assert(nX * 32 < INT_MAX);
    assert(nY * 32 < INT_MAX);

    int sx = nX * 32;
    int sy = nY * 32;

    unsigned int ux = sx;
    unsigned int uy = sy;

    nFixed = (ux << 16) | uy;
}

I've got rid of the pointer casts, which (as others have pointed out) break the strict aliasing rule. I've also used int instead of short. There's generally no point having short auto variables, since they're widened to ints before computations anyway. (It's a good job they are, as shifting a short by 16 bits would not be very useful.) I've added some checks so your debug builds can find out if the float-to-integer conversion will overflow, which causes undefined behaviour.

0

精彩评论

暂无评论...
验证码 换一张
取 消