tags:

views:

312

answers:

2

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?

+2  A: 

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
A: 
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
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
Right, so `(sizeof(input) + sizeof(unsigned long) - 1) / sizeof(unsigned long)` is safer, but I was lazy and wrote the short way instead ;-)
ephemient