Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

One 32bit Long into 4 8bit Chars

Name: Anonymous 2010-06-28 7:43

In C code

I'm gonna ask a stupid question here, but I'm not sure I trust my code so I want to hear if you can tell me what's wrong with my approach

Right now, the code goes

long data

char data0
char data1
char data2
char data3

data0 = data;
data1 = data >> 8;
data2 = data >> 16;
data3 = data >> 24;

but I'm not sure that's the best approach, or even a good approach. It works, which is most important obviously, but I have this nagging feeling that there's something very not Best Practices about this approach and I can't shake that feeling.

Name: Anonymous 2010-06-28 17:58

>>35
Yeah, enjoy doing stuff manually.
If anything, >>1-chan should at least use an array:
long data = (...);
char bytes[sizeof(data)];
for (int i = 0; i < sizeof(data); ++i, data >> 8)
    bytes[i] = 0xFF&data;

Note that this won't work either on architectures where bytes don't have 8 bits.

Combining it with htonl() is just making a bad solution worse.
I don't see how.

Name: 35 2010-06-29 2:11

>>36,45
Your code is actually longer, more error prone, more obfuscated, and much slower without a good optimizer.

Why the fuck do you both want to roll four trivial lines of code into a loop? Unless you unroll it you've just added a bunch of jumps and branches and arithmetic to something that requires barely any processor instructions (and could be eliminated completely with the slightest optimization.)

You seem like the kind of programmers that fucking template everything because hey, it has to be generic and reusable!

>>39
On most mobile platforms that run C (including the iPhone), you compile against x86 to run in a simulator and against ARM to run on device. So yeah, anyone who has done embedded knows about endianness. Using a union and then hacking it to work by using htonl() is just stupid. It's also technically a violation of the standard, although most compilers do support type-punning through a union.

Also, another good reason to explicitly specify unsigned char is that char is by default unsigned on ARM and signed on x86; the standard does not specify whether char is signed. So you may get working code on ARM that suddenly carries the sign bit on x86.

>>39
only half the topic has been covered
What am I missing?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List