Splitting a number into bytes using pointers. Pointers in C ++ and how to work with them
Вставка
- Опубліковано 2 жов 2024
- In this video, we'll talk about how you can split numbers that take up two or more bytes of memory space into an array of single-byte numbers using pointers. And then, also using pointers, collect into the original number. This method is perhaps the most effective, because does not require any mathematical or logical operations, and uses one of the features of the C / C ++ language - the ability to directly access memory cells by their address and read or modify their contents.
2 other ways (division and bit shift) - • Разбиваем числа (word,...
Link to sketch using pointers from the video - drive.google.c...
Как тебе такой способ, по сути в 3 строчки?
uint32_t joinVal, val = 0x12345678;
void setup() {
Serial.begin(9600);
uint8_t *splitVal = (uint8_t *)&val;
uint8_t *pointer = (uint8_t *)&joinVal;
while (*splitVal) *pointer++ = *splitVal++;
Serial.println(joinVal, HEX);
}
void loop() {
}
Спасибо! Это пожалуй самый компактный вариант, что я видел.
наверное можно еще проще через структуру union :)
Возможно и проще. Не уверен, что по скорости быстрее. Надо сравнивать. Думаю, через указатели самый быстрый способ.