1

Using c, I have defined a byte and word as follows:

typedef unsigned char byte;
typedef union {
    byte b[4];
    unsigned long w;
} word;

This allows me to easy go from words to bytes, but I'm not sure of a good way to go the other way. Is it possible to do something like cast from byte* to word* or do I have to stick with iteratively copying bytes to words?

giroy
  • 2,203
  • 6
  • 27
  • 38
  • It's not clear to me what, exactly, you're trying to do. If you want the byte values comprising a word, then cast the word pointer to a byte pointer. For the reverse, cast the byte pointer to a word pointer but only if you know the bytes are properly aligned. – Steve Emmerson Jan 22 '10 at 04:39
  • Do you want each individual byte to be stretched into a word, or do you want 4 bytes to make up a word? – littlegreen Jan 22 '10 at 04:45
  • I want the latter. So if I have 16 bytes, it will make 4 words of 4 bytes. I also need it to be able to properly pad array which don't have a multiple of 4 of bytes. – giroy Jan 22 '10 at 04:59
  • By the way, even though everybody does it, assigning to one member of a union then retrieving a different member is undefined behavior by the C specification. – ephemient Jan 22 '10 at 05:57

2 Answers2

3

One of the great and terrible things about c is you can take a void pointer and cast it to anything. As long as you know what you are doing it will work, but not something you want to get in the habit of.

rerun
  • 25,014
  • 6
  • 48
  • 78
1
const byte input[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
unsigned long output[sizeof(input) / sizeof(unsigned long)];
memcpy(output, input, sizeof(input));
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • This answer is more reliable than the question since it can work even when unsigned long has a different size than 4. But it's dangerous if someone hands the original poster a byte array whose length isn't a multiple of sizeof(unsigned long). – Windows programmer Jan 22 '10 at 05:09
  • Right, so `(sizeof(input) + sizeof(unsigned long) - 1) / sizeof(unsigned long)` is safer, but I was lazy and wrote the short way instead ;-) – ephemient Jan 22 '10 at 05:34