
Different value when converting into different type
Quote:
>Dear all,
> I have the following the code
> int * iByte = (int *) PtrTbl[k+1][i]; // PtrTbl[k+1][i] has the value
>"hT"
> The exact value for the hT (in hex) is 26708 in decimial. However, after
>this command, the iByte value is 21608. I don't know why the value is not
>equal. Can anyone tell me? Thank you for all of your help.
You are evaluating the int wrong-endian. You must be using an old
system if your int is only two bytes.
"hT" is 0x685400. Only the first two bytes participate. The decimal
value of 0x6854 is 36708 as you claim.
However, the hardware that you are running on (Intel or compatible) is
little-endian. This means that when you look at memory, the lower
order byte is before the high order byte. The two bytes 0x68 and
0x54, in order, have the value 0x5468. The decimal equivalent is
21608. Try the following to convince yourself:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
unsigned char *c = "hT";
unsigned short s;
int i;
memcpy(&s, c, sizeof s);
for (i = 0; c[i]; i++)
printf("i: %d, char %c, hex %x, dec %u\n", i, c[i], c[i],
c[i]);
printf("hex %x, dec %u\n", s, s);
getchar();
return 0;
Quote:
}
<<Remove the del for email>>