我制作了将给定值(从数组指针)拆分为字节的函数。为简单起见,我使用一个字节值。 为什么我在打印值时得到奇怪的数字?
void writePage(uint16_t address, uint64_t *data, uint8_t const len, uint8_t const bPD)
{
uint8_t pageBuffer[32];
uint8_t bytes2Write = len * bPD;
for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
{
std::cout << int(dataIndex) << std::endl;
std::cout << data[dataIndex] << std::endl;
for (uint8_t i = 0; i < bPD; i++)
{
pageBuffer[i + (dataIndex * bPD)] = ((data[dataIndex] >> 8 * i) & 0xFF);
std::cout << int(pageBuffer[i + (dataIndex * bPD)]) << std::endl << std::endl;
}
}
}
int main()
{
uint8_t array[3] = { 255, 20, 30 };
std::cout << int(array[0]) << int(array[1]) << int(array[2]) << std::endl;
writePage(0, (uint64_t*)array, 3, 1);
getch();
return 0;
}
输出
2552030
0
119944479905023
255
1
70453687222272
0 2
0
0
最佳答案
如果你的目标是采用任何类型,并分解字节,几乎总是这样做的方式是将指向该类型的指针转换为 char *
并使用 字符*
。
这是一个使用您的代码精简版的示例。
#include <iostream>
struct foo
{
int x;
double y;
char z;
};
void writePage(uint16_t address, char *data, uint8_t const len)
{
for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
{
std::cout << (int)data[dataIndex] << std::endl;
}
}
int main()
{
uint8_t array[3] = { 255, 20, 30 };
std::cout << int(array[0]) << " " << int(array[1]) << " " << int(array[2]) << std::endl;
writePage(0, reinterpret_cast<char *>(&array[0]), sizeof(array));
foo f;
f.x = 10;
f.y = 20;
f.z = 'g';
std::cout << "Here are the bytes of foo, which has a sizeof(foo) as " << sizeof(foo) << "\n" ;
writePage(0, reinterpret_cast<char *>(&f), sizeof(f));
return 0;
}
输出:
255 20 30
-1
20
30
Here are the bytes of foo, which has a sizeof(foo) as 24
10
0
0
0
0
0
0
0
0
0
0
0
0
0
52
64
103
-54
-117
-54
-2
127
0
0
关于c++ - 从数组指针获取奇怪的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917751/