I have four characters as ch1,ch2,ch3,ch4. I am reading a binary file. Que- What following code indicates?
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'; 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?
The fact that ch[1234] are characters is not relevant: they are just numeric values.
Just think it's something like this:
ch1 = 0x10;
ch2 = 0x20;
ch3 = 0x30;
ch4 = 0x40;
your output value will be hex value 0x10203040.
What is output is a single int that has four chars inside of it. You can think of it like this:
My four chars are: 0x00, 0x02, 0x53, 0xEF
ch1 << 24 = 0x 00 000000
ch2 << 16 = 0x00 02 0000
ch3 << 8 = 0x0000 53 00
ch4 = 0x000000 EF
Next with bitwise 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. The <<
operator is a shift left operator, so if (in binary)
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.
Break it down by steps:
hTTF
or returns EOF;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.