C++:了解我的计算机如何存储字节
C++: Finding out how my computer stores bytes
得到了这个作业,我们将检查我们的计算机如何存储字节等等,我无法真正掌握如何获得正确答案,但代码几乎解释了我的想法。
提前谢谢。
#include <iostream>
using namespace std;
union hexNumber{
signed short normal;
signed short twoByte1, twoByte2;
signed short fourByte1, fourByte2, fourByte3, fourByte4;
} theNumber;
int main()
{
int number;
cout << "Write your number (int): " << endl;
cin >> number;
theNumber.normal = number;
cout << "nNormal: " <<std::hex << theNumber.normal << endl;
theNumber.twoByte1 = number;
theNumber.twoByte2 = number;
(theNumber.twoByte1 & 0x00001111);
(theNumber.twoByte2 & 0x11110000);
cout << "nTwoByte1: " <<std::hex << theNumber.twoByte1 << endl;
cout << "TwoByte2: " <<std::hex << theNumber.twoByte2 << endl;
theNumber.fourByte1 = number;
theNumber.fourByte2 = number;
theNumber.fourByte3 = number;
theNumber.fourByte4 = number;
(theNumber.fourByte1 & 0x00000011);
(theNumber.fourByte2 & 0x00001100);
(theNumber.fourByte3 & 0x00110000);
(theNumber.fourByte4 & 0x11000000);
cout << "nfourByte1: " << std::hex << theNumber.fourByte1 << endl;
cout << "fourByte2: " << std::hex << theNumber.fourByte2 << endl;
cout << "fourByte3: " << std::hex << theNumber.fourByte3 << endl;
cout << "fourByte4: " << std::hex << theNumber.fourByte4 << endl;
system("pause");
}
它们都打印相同的东西。
它们打印都是一样的,因为你在联合中只使用short
。你可能想写的是:
union HexNumber {
int full_number; // assuming 'int' is 4-bytes; int32_t would be
unsigned char b[4]; // uint8_t would be better
} theNumber;
theNumber.full_number = number;
std::cout << std::hex << (int)theNumber.b[0] << " " << (int)theNumber.b[1]
<< " " << (int)theNumber.b[2] << " " << (int)theNumber.b[3] << std::endl;
你似乎真正想要的是:
union hexNumber{
int fourBytes;
short twoBytes[2];
char oneByte[4];
} theNumber;
现在,hexNumber
对象可以被视为int
,2 short
的数组或4 char
的数组。
但请注意,int
、short
和char
的大小是实现定义的。更跨平台的版本是:
union hexNumber{
std::int32_t fourBytes;
std::int16_t twoBytes[2];
std::int8_t oneByte[4];
} theNumber;
这些类型可从<cstdint>
标头获得。
这些行:(theNumber.fourByte1 & 0x00000011);
他们什么都不做。结果不会存储在任何地方。你的意思是
theNumber.fourByte1 = (theNumber.fourByte1 & 0x00000011);
联合中应该有不同的数据类型,此外,您应该添加一个长度为零的位字段。
std::int32_t force_align : 0 ;
确保对齐。
相关文章:
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 为什么 bool 和 _Bool 如果它们在内存中占用 1 个字节,它们只能存储 0 或 1
- 如何在 XML 中正确存储原始字节数据并恢复它?
- 哪些值存储在对齐的结构/类对象的填充字节中
- 如何使用连接器 c++ 在 mySQL 表二进制(16) 字段中存储 c++ 字节数组?
- 使用字节向量作为其他类型的原始存储是一种好的做法吗
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 比较存储在 std::string 中的数据中的字节数
- 是否值得使用位移在单个字节中存储多个小数据成员?
- 为什么当我使用双精度时,Qt<->Matlab 正确写入和读取我的字节,但存储 uint32 的字节不正确?
- 一个对象什么时候可以有非零大小的一个,但不能同时具有一个或多个字节的存储
- C++如何从文件中读取十六进制字节并将其存储为指针
- 我如何将整数转换为存储在字符阵列中的十六进制字节
- 将Protobuf字节类型存储在二进制文件中
- 您可以在Arduino字符串中存储多少字节?
- 在 c++ 中存储字节模式
- C++:了解我的计算机如何存储字节
- 如何使用节俭C++ API 在 HBase 中存储字节数组(突变结构中的值是文本 ..)
- 编译lua代码,存储字节码,然后加载并执行它
- 为什么 file.write() 不按照我给出的顺序存储字节?C++