简体   繁体   English

如何将 4 字节 uint8 数组重构为 uint32 integer

[英]How to reconstruct a 4 byte uint8 array into a uint32 integer

I have a web app (javascript) that needs to send a arduino(ESP32) a 12bit value (0x7DF).我有一个 web 应用程序(javascript),它需要向 arduino(ESP32)发送一个 12 位值(0x7DF)。 I have a websocket connection that only accepts a Uint8_t payload, so I split the value into 4 bytes (Uint8_t).我有一个仅接受 Uint8_t 有效负载的 websocket 连接,因此我将值拆分为 4 个字节(Uint8_t)。 I can send the array to the arduino, but how do i reconstruct it back into a 32bit value?我可以将数组发送到 arduino,但我如何将它重建回 32 位值?

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.感谢任何帮助编辑:我的转换 function 有一个测试变体,而不是原始解决方案。 fixed that.解决了这个问题。

On Arduino, int s 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).在 Arduino 上, int是 16 位的,因此id[0] << 24 (将id[0]uint8_t提升到int )是未定义的(无论如何都无法保存该值,使其始终为 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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM