M
mohangupta13
with ref to question 16.7 in FAQ's :
struct mystruct {
char c;
long int i32;
int i16;
} s;
unsigned char *p = buf;
s.c = *p++;
1. s.i32 = (long)*p++ << 24;
2. s.i32 |= (long)*p++ << 16;
3. s.i32 |= (unsigned)(*p++ << 8);
s.i32 |= *p++;
s.i16 = *p++ << 8;
s.i16 |= *p++;
for unpacking a buffer as "buf " here how are all these casts
justified , i mean in line 2 if *p was equal to something like 128
(assuming 8-bit char) then when casting it to long it would have been
sign extended (as i understand it ) as:
expression result bit
representation
(unsigned char) 128 10000000
(long)128 (11111111)^3
10000000 (it is sign extended)
(long)128 <<16 11111111 10000000
(00)^8
(a)^b here means string of 'a' repeated 'b' times
so now how is the 'bitwise or ' in line 2 justified as the value which
was 128 has changed to something else due to the cast to long and the
subsequent left shift.
same for line 3 , if *p is 8-bit then left shifting it by 8 will
result in what ???
I really think I am just not able to grasp the concept of shifting and
sign extended thing in casts ..
Can anyone kindly explain it with some easy to understand example ???
Thanks a lot
Mohan Gupta
struct mystruct {
char c;
long int i32;
int i16;
} s;
unsigned char *p = buf;
s.c = *p++;
1. s.i32 = (long)*p++ << 24;
2. s.i32 |= (long)*p++ << 16;
3. s.i32 |= (unsigned)(*p++ << 8);
s.i32 |= *p++;
s.i16 = *p++ << 8;
s.i16 |= *p++;
for unpacking a buffer as "buf " here how are all these casts
justified , i mean in line 2 if *p was equal to something like 128
(assuming 8-bit char) then when casting it to long it would have been
sign extended (as i understand it ) as:
expression result bit
representation
(unsigned char) 128 10000000
(long)128 (11111111)^3
10000000 (it is sign extended)
(long)128 <<16 11111111 10000000
(00)^8
(a)^b here means string of 'a' repeated 'b' times
so now how is the 'bitwise or ' in line 2 justified as the value which
was 128 has changed to something else due to the cast to long and the
subsequent left shift.
same for line 3 , if *p is 8-bit then left shifting it by 8 will
result in what ???
I really think I am just not able to grasp the concept of shifting and
sign extended thing in casts ..
Can anyone kindly explain it with some easy to understand example ???
Thanks a lot
Mohan Gupta