0

I am writing a program and using memcpy to copy some bytes of data, using the following code;

#define ETH_ALEN 6
unsigned char sourceMAC[6];
unsigned char destMAC[6];
char* txBuffer;
....
memcpy((void*)txBuffer, (void*)destMAC, ETH_ALEN);
memcpy((void*)(txBuffer+ETH_ALEN), (void*)sourceMAC, ETH_ALEN);

Now I want to copy some data on to the end of this buffer (txBuffer) that is less than a single byte or greater than one byte, so it is not a multiple of 8 (doesn't finish on a whole byte boundary), so memcpy() can't be used (I don't believe?).

I want to add 16 more bits worth of data which is a round 4 bytes. First I need to add a value into the next 3 bits of txtBuffer which I have stored in an int, and a fourth bit which is always 0. Next I need to copy another 12 bit value, again I have this in an int.

So the first decimal value stored in an int is between 0 and 7 inclusively, the same is true for the second number I mention to go into the final 12 bits. The stored value is within the rang of 2^12. Should I for example 'bit-copy' the last three bits of the int into memory, or merge all these values together some how?

Is there a way I can compile these three values into 4 bytes to copy with memcpy, or should I use something like bitset to copy them in, bit at a time?

How should I solve this issue?

Thank you.

jwbensley
  • 10,534
  • 19
  • 75
  • 93
  • 3
    If you need to cite *yourself* in your own post to make your post understandable, it's time for a proper rewrite. – Kerrek SB Oct 29 '12 at 17:13
  • 2
    Sounds like you need to experiment with the bit-shifting operator < – Darren Oct 29 '12 at 17:18
  • 1
    A couple of things to consider when bit twiddling is that char is not guaranteed to be one byte on all platforms, and that the order of bytes in an int may be either little-endian or big-endian. – Darren Oct 29 '12 at 17:33
  • Hmm good point, but is there anything that can easily be done about this, or am I first going to have to somehow check the kind of bit ordering used then write the code twice for the opposing orderings? – jwbensley Oct 29 '12 at 17:40

1 Answers1

1

Assuming int is 4 bytes on your platform

int composed = 0;

int three_bits = something;
int twelve_bits = something_else;

composed = (three_bits & 0x07) | (1 << 3) | ((twelve_bits << 4) & 0xFFFFFF0);
  • Very nice and succinct, thanks! This has given me some good food for thought and homework to check. :) – jwbensley Oct 29 '12 at 17:41
  • Also, if you want to make sure you know the size of your types (such as `int`s, etc.), you can use `stdint.h`. It provides types such as `int32_t`, `uint32_t`. – Matt Kline Oct 29 '12 at 18:21