【发布时间】:2022-01-19 07:44:04
【问题描述】:
我正在学习C++,想知道是否可以将结构对象分解为位序列?
// The task is this! I have a structure
struct test {
// It contains an array
private:
int arr [8];
public:
void init () {
for (int i = 0; i <8; i ++) {
arr [i] = 5;
}
}
};
int main () {
// at some point this array is initialized
test h;
h.init ();
// without referring to the arr field and its elements, we must convert the structure to this format
// we know that int is stored there, and these are 32 bits -> 00000000 00000000 00000000 00000101. 00000000 00000000 00000000 00000101. - and there are 8 such pieces by number
// elements in the array
return -1;
}
好吧,我们也知道数组的大小。我们需要将结构对象转换为位序列:
00000000000000000000000000000101000000000000000000000000000001010000000000000000000000000000010100000000000000000000000000000101000000000000000000000000000001010000000000000000000000000000010100000000000000000000000000000000010100000000000000000000000000000101 P>
【问题讨论】:
-
当然可以。只需创建一个函数来获取数组的每个元素并打印其位。或者您可以将结构对象
h的内容复制到一个字节数组中并打印该数组中的位(但要注意填充!)。 -
你试过什么?你研究过位运算符吗?您在尝试使用它们时遇到了什么问题?
-
关键字是“序列化”,在运行时平台之间交换数据很常见