Home > Software design >  How to get a pointer to the bytes of a uint32_t
How to get a pointer to the bytes of a uint32_t

Time:08-14

I'm trying to create a complete uint32_t using vector of uint8_t bytes. It should be filled iteratively. It can happen in any of the following ways:

  • 1 byte and 3 bytes.
  • 2 bytes and 2 bytes.
  • 4 bytes.
  • 3 bytes and 1 byte.
    uint32_t L = 0;
    uint32_t* LPtr = &L;
    std::vector<uint8_t> data1 = {0x1f, 0x23};
    memcpy(LPtr, data1.data(), 2);
    EXPECT_EQ(0x231f, L);

Above works fine (first two bytes). But following is not (with the two sets of bytes).

    uint32_t L = 0;
    uint32_t* LPtr = &L;
    std::vector<uint8_t> data1 = {0x1f, 0x23};
    std::vector<uint8_t> data2 = {0x3a, 0xee};
    memcpy(LPtr, data1.data(), 2);
    memcpy(LPtr, data2.data(), 2);
    EXPECT_EQ(0x231f, L);
    EXPECT_EQ(0x231fee3a, L);

The issue I feel is LPtr does not point to the next byte that should be filled next. I tried LPtr 2 which is not pointing to individual byte of uint32_t.

This should be done using memcpy and output should go to uint32_t. Any idea to get this sorted?

Endianness is not an issue as of now. It can be corrected once the uint32_t is completed (when eventually 4 bytes get copied).

Any help is appreciated!

CodePudding user response:

The problem is you're using a pointer to uint32_t so incrementing it won't make it iterate by 1 byte, only by 4 bytes. Here is a version which populates all bytes of L, but it's still messing with endianness:

uint32_t gimmeInteger(std::vector<uint8_t> data1, std::vector<uint8_t> data2)
{
  assert((data1.size() == 2));
  assert((data2.size() == 2));
  uint32_t L = 0;
  uint8_t* LPtr = reinterpret_cast<uint8_t*>(&L);
  memcpy(LPtr, data1.data(), 2);
  memcpy(LPtr 2, data2.data(), 2);
  return L;
}
  •  Tags:  
  • c
  • Related