Yatra.com Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
4 should be sizeof(int) - or sizeof(whatever-type-you-convert).
But if the size of integer is known it is much better (and faster to execute) to write a macro to swap the bytes.
// if sizeof(int) == 4
#define SWITCH_ENDIANNESS(i) ( \
((i)<<24) | \
((i<<8)&0x0000FF00)) | \
((i>>8)&0x00FF0000)) | \
((i>>24)&0x000000FF)) )
Alternatively swap the last-byte with first, and the middle-bytes.
// suppose that sizeof(int) == 4
void switch_endianness(int *i) {
char *c = (char *)i;
int temp;
// first swap 0th and 3rd byte
temp = *c; *c = *(c+3); *(c+3) = temp;
// and then swap 1st and 2nd byte
temp = *(c+1); *(c+1) = *(c+2); *(c+2) = temp;
}
Assuming that the number "no" passed to fun endianess need to be changed .
- saikat January 25, 2012int fun ( int no){
int i = 0,k ; char * c;
c = (char *)(&no); // now c will point to the 1st 8 bits of no.
for( int j =0; j<4;j++){
k = (int)(*c);
i = i | k;
i << 8;
c++
}
return (i)
}