[slightly OT] Portable float packing/unpacking

and frankly, if you want to get any work done, you won’t either. Same
with this float/int aliasing nonsense. Cast the thing or use a union and
if it breaks on your black-and-white Palm Pilot, write some inline asm

I hope you mean “cast the thing to (char*)”, because otherwise:

Man, I’m so done with this conversation.

–ryan.

… and so will the compiler be. However the above code
is broken. You must do this:

    *(unit32*)(void*)&f

Sorry, (void*) does not help you with the aliasing rules.
Though (char*) does, I think you still lose because you
then cast to a type that is not permitted to alias with the
first type.

and it may fail if the size and alignment of float32 and
uint32 are not the same.

Sure. In practice, both float and unsigned are 32-bits on
all 32-bit and 64-bit platforms. Because of the need to
avoid adding holes in the selection of types available,
they won’t be switching to a larger size decades from now.

Thanks for all the help so far. The situation is far more fragile than
I had previously thought. Is there ANY safe assignment in C? :slight_smile:

Ok, so, can these functions be made any ‘safer’ or is this as good
as it’s going to get?

void float32_packl(char n[4], float32 f)
{
uint32 ui = *(uint32 *)(void *) &f;

That’s wrong.

The correct way with [a bunch of ways]:
[snip]

Is there any reason you can’t just use a local array of unsigned char,
memcpy, and htonl?

– JoshOn 2/13/06, Albert Cahalan wrote:

On 2/13/06, mal content <artifact.one at googlemail.com> wrote:

On 2/13/06, skaller wrote:


SDL mailing list
SDL at libsdl.org
http://www.libsdl.org/mailman/listinfo/sdl

Is there any reason you can’t just use a local array of unsigned char,
memcpy, and htonl?

There is none that I know of. I dearly hope it isn’t legal for
a compiler to make aliasing assumptions over a memcpy(),
though I do recall that memcpy() can be a built-in function.
That’d be interesting to discuss on a gcc mailing list.

The whole (char*) exception is to allow implementation of
things like memcpy(), even though in reality it isn’t often
implemented that way.

Some people worry that memcpy() might be too slow. Probably
this is a silly thing to worry about.On 2/15/06, Joshua Oreman wrote:

and frankly, if you want to get any work done, you won’t either. Same
with this float/int aliasing nonsense. Cast the thing or use a union and
if it breaks on your black-and-white Palm Pilot, write some inline asm

I hope you mean “cast the thing to (char*)”, because otherwise:

Man, I’m so done with this conversation.

–ryan.

You are much more patient than I… I gave up on it long ago. I just
have a habit of reading your posts.

Bob PendletonOn Tue, 2006-02-14 at 19:38 -0800, Ryan C. Gordon wrote:

SDL mailing list
SDL at libsdl.org
http://www.libsdl.org/mailman/listinfo/sdl


±-------------------------------------+