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?

4
  • 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. Commented Jan 22, 2010 at 4:39
  • Do you want each individual byte to be stretched into a word, or do you want 4 bytes to make up a word? Commented Jan 22, 2010 at 4: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. Commented Jan 22, 2010 at 4: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. Commented Jan 22, 2010 at 5:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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));

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.