简体   繁体   English

c ++如何解释二进制数

[英]How does c++ interpret a binary number

I have a general question about binary numbers in c++. 我对c ++中的二进制数有一个普遍的疑问。 I am reading in a binary file of 32-bit numbers, and then writing these numbers to a text file. 我正在读取32位数字的二进制文件,然后将这些数字写入文本文件。 My question is, when I do 我的问题是,当我这样做的时候

long int temp;
temp = ( fileBuf[N * 4 * i + 4 * j + 0] << 24 |
         fileBuf[N * 4 * i + 4 * j + 1] << 16 |
         fileBuf[N * 4 * i + 4 * j + 2] << 8  | 
         fileBuf[N * 4 * i + 4 * j + 3] << 0  );
myfile1 << temp << "\t";

does c++ understand that I want it to reinterpret the binary as a decimal number? c ++是否理解我希望它将二进制文件重新解释为十进制数?

All numbers inside of a C++ int variable are binary. C ++ int变量中的所有数字都是二进制的。 The conversion to or from decimal occurs as the number is read or written, or as the compiler converts it from a constant into code. 在读取或写入数字时,或者编译器将其从常量转换为代码时,会发生到十进制或从十进制的转换。

If I interpret this question as "Will this do what I want it to?" 如果我将这个问题解释为“这会做我想要的吗?” then the answer is yes , as long as what you want it to do is read a 32 bit, big endian integer out of a buffer (presumably loaded from a file) at offset 4 * N * i + 4 * j . 然后答案是肯定的 ,只要您想要它做的是从偏移量为4 * N * i + 4 * j的缓冲区(可能是从文件加载)中读取32位大端序列。

Assuming of course that fileBuf is declared as a character or unsigned character type. 当然假设fileBuf被声明为字符或无符号字符类型。 It would behave differently if it were, for example, an array of shorts. 如果它是例如一系列短裤,它的行为会有所不同。 You'd end up with a mutilated representation of a 64 bit quantity. 你最终会得到一个64位数量的残缺表示。

实际上,在最后一行打印之前,该数字不会转换为十进制数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM