[英]Is it possible to convert from 4x Uint8 into Uint32 using typed arrays in JavaScript?
[英]How to reconstruct a 4 byte uint8 array into a uint32 integer
我有一個 web 應用程序(javascript),它需要向 arduino(ESP32)發送一個 12 位值(0x7DF)。 我有一個僅接受 Uint8_t 有效負載的 websocket 連接,因此我將值拆分為 4 個字節(Uint8_t)。 我可以將數組發送到 arduino,但我如何將它重建回 32 位值?
這是我用來將其轉換為字節的代碼:
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]
我已經嘗試了其他問題中給出的很多選項,但沒有一個有效。 這是他們的建議:
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.
感謝任何幫助編輯:我的轉換 function 有一個測試變體,而不是原始解決方案。 解決了這個問題。
在 Arduino 上, int
是 16 位的,因此id[0] << 24
(將id[0]
從uint8_t
提升到int
)是未定義的(無論如何都無法保存該值,使其始終為 0)。
您需要事先進行一些演員表:
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.