Home > Net >  How to reconstruct a 4 byte uint8 array into a uint32 integer
How to reconstruct a 4 byte uint8 array into a uint32 integer

Time:12-09

I have a web app (javascript) that needs to send a arduino(ESP32) a 12bit value (0x7DF). I have a websocket connection that only accepts a Uint8_t payload, so I split the value into 4 bytes (Uint8_t). I can send the array to the arduino, but how do i reconstruct it back into a 32bit value?

This is the code i am using to turn it into bytes:

const uInt32ToBytes = (input) => {
  const buffer = Buffer.alloc(4)
  buffer.writeUInt32BE(input, 0)
  return [
    buffer[0],
    buffer[1],
    buffer[2],
    buffer[3]
  ]
}

//With an input of 0x7DF i get an output of [0, 0, 7, 223]

I have tried a lot of options given in other questions but none work. This is what they suggested:

uint32_t convertTo32(uint8_t * id) {
  uint32_t bigvar = (id[0] << 24)   (id[1] << 16)   (id[2] << 8)   (id[3]);
  return bigvar;
}
//This returns an output of 0. 

Any help is appreciated EDIT: My convert function has a test variant and not the original solution. fixed that.

CodePudding user response:

On Arduino, ints are 16 bit, so id[0] << 24 (which promotes id[0] from uint8_t to int) is undefined (and wouldn't be able to hold the value anyways, making it always 0).

You need some casts beforehand:

return (static_cast<uint32_t>(id[0]) << 24)
     | (static_cast<uint32_t>(id[1]) << 16)
     | (static_cast<uint32_t>(id[2]) << 8)
     | (static_cast<uint32_t>(id[3]));

  • Related