Page 1 of 1

wikipedia

Posted: Fri Oct 09, 2009 10:54 am
by MarauderIIC
So I was browsing around wikipedia, and the article on Type punning has some interesting examples and caveats of those examples.

Code: Select all

bool is_negative(float x) {
    return (x < 0.0);
}
However, supposing that floating-point comparisons are expensive, and also supposing that float is represented according to the IEEE floating-point standard, and integers are 32 bits wide, we could engage in type punning to extract the sign bit of the floating-point number using only integer operations:

Code: Select all

bool is_negative(float x) {
    unsigned int *ui = (unsigned int *)&x;
    return (*ui & 0x80000000 != 0);
}
Although most programming style guides frown on any kind of type punning, this kind of type punning is more dangerous than most. Whereas the former relied only on guarantees made by the C programming language about structure layout and pointer convertibility, this example relies on assumptions about a system's particular hardware. Some situations, such as time-critical code that the compiler otherwise fails to optimize, may require dangerous code. In these cases, documenting all such assumptions in comments helps to keep the code maintainable.
And it also has an example using union. It's worth a read.

-
I was reading the wikipedia article on C++ to see if I'd learn anything. And within two clicks (statically typed -> type punning), I did! =)

Re: wikipedia

Posted: Fri Oct 09, 2009 11:31 am
by captjack
This speaks a lot to portable programming. Depending on one's point of view (or experience), writing code as portable as possible is generally considered "a good thing". I've seen this kind of thing a lot in kernel programming (especially bootstrap code) but it's just as relevant to game programming. I'd like to have my code run on as much hardware as possible to get the most potential for a user base.

Two huge "gotchas" in programming are not checking function return values and assuming too much about cross-platform compatibilities (big endian vs. little endian come to mind).

-capt jack

Re: wikipedia

Posted: Fri Oct 09, 2009 5:36 pm
by MarauderIIC
My thought was that if you're programming for a console,

Code: Select all

bool is_negative(float x) {
    unsigned int *ui = (unsigned int *)&x;
    return (*ui & 0x80000000 != 0);
}
would be perfectly acceptable.

Re: wikipedia

Posted: Sun Oct 11, 2009 7:09 am
by Falco Girgis
MarauderIIC wrote:My thought was that if you're programming for a console,

Code: Select all

bool is_negative(float x) {
    unsigned int *ui = (unsigned int *)&x;
    return (*ui & 0x80000000 != 0);
}
would be perfectly acceptable.
A little-endian console.