[英]Shift operator and bitwise or
I have four characters as ch1,ch2,ch3,ch4. 我有四个字符,分别为ch1,ch2,ch3,ch4。 I am reading a binary file.
我正在读取一个二进制文件。 Que- What following code indicates?
Que-以下代码表示什么?
int GetLong(FILE * hTTF)
{
int ch1 = getc(hTTF);
int ch2 = getc(hTTF);
int ch3 = getc(hTTF);
int ch4 = getc(hTTF);
if ( ch4 == EOF )
return( EOF );
return( (ch1<<24)|(ch2<<16)|(ch3<<8)|ch4 );
}
consider ch1='k',ch2='e',ch3='r',ch4='n'; 考虑ch1 ='k',ch2 ='e',ch3 ='r',ch4 ='n'; Tell me output and why this is so?.
告诉我输出,为什么会这样? I am not understanding output value.
我不了解产值。 Que-What is this conversion (ch1<<24)|(ch2<<16)|(ch3<<8)|ch4 What we achive by doing this?
Que-此转换是什么(ch1 << 24)|(ch2 << 16)|(ch3 << 8)| ch4我们这样做会得到什么?
The fact that ch[1234] are characters is not relevant: they are just numeric values. ch [1234]是字符这一事实无关紧要:它们只是数字值。
Just think it's something like this: 只是想像这样:
ch1 = 0x10;
ch2 = 0x20;
ch3 = 0x30;
ch4 = 0x40;
your output value will be hex value 0x10203040. 您的输出值为十六进制值0x10203040。
What is output is a single int that has four chars inside of it. 输出的是单个int,其中包含四个字符。 You can think of it like this:
您可以这样想:
My four chars are: 0x00, 0x02, 0x53, 0xEF
我的四个字符是:
0x00, 0x02, 0x53, 0xEF
ch1 << 24 = 0x 00 000000 ch1 << 24 = 0x 00 000000
ch2 << 16 = 0x00 02 0000 ch2 << 16 = 0x00 02 0000
ch3 << 8 = 0x0000 53 00 ch3 << 8 = 0x0000 53 00
ch4 = 0x000000 EF ch4 = 0x000000 EF
Next with bitwise ors. 接下来与按位ors。
x | 0 = x
1 | x = 1
So: 所以:
0x00000000
0x00020000
0x00005300
0x000000EF
----------
0x000253EF
The return will be a 32 bit value where the most significant 8 bits is ch1, next 8 bits is ch2 and so on. 返回值将是一个32位值,其中最高有效8位是ch1,接下来的8位是ch2,依此类推。 The
<<
operator is a shift left operator, so if (in binary) <<
运算符是左移运算符,因此if(以二进制形式)
ch1 = 10101010
then (dots added for readability) 然后(添加点以提高可读性)
ch1 << 24 = 10101010.00000000.00000000.00000000
and so on. 等等。 The
|
|
operator is an bitwise OR operator, so it just combines the variously shifted ch
values. 运算符是按位或运算符,因此它仅组合了各种移位的
ch
值。
Break it down by steps: 按步骤细分:
hTTF
or returns EOF; hTTF
指向的文件中读取4个8位字节,或者返回EOF;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.