i want to transmit data by bit unit so i was access data with char* variable. here is my code.
int main()
{
//initiate int variable and casting with char*
int a = 65;
cout << a << endl;
char* p = reinterpret_cast<char*>(&a);
cout << "------------------" << endl;
//check char* p is pointing &a
cout << &a << endl;
printf("0x%x\n", p);
cout << "------------------" << endl;
//access int variable with byte unit
cout << (int)*(p + 0) << endl;
cout << (int)*(p + 1) << endl;
cout << (int)*(p + 2) << endl;
cout << (int)*(p + 3) << endl;
cout << "------------------" << endl;
//initiate int variable and assemble with char* access in way 1
int* b = new int(0);
*b = *(p + 0) << 24;
*b += *(p + 1) << 16;
*b += *(p + 2) << 8;
*b += *(p + 3);
cout << *b << endl;
cout << "------------------" << endl;
//initiate int variable and assemble with char* access in way 2
*b = *(p + 0);
*b += *(p + 1) << 8;
*b += *(p + 2) << 16;
*b += *(p + 3) << 24;
cout << *b << endl;
return 0;
}
and output like this.
65 -> variable a is 65
------------------
0x61ff04
0x61ff04 -> char* p is pointing right
------------------
65
0
0
0 -> access with byte unit
------------------
1090519040 -> way 1
------------------
65 -> way 2
when i access data by byte unit that first address pointing data shows '65' so i think this system is big endian.
so i thought if i want to transmit 'a' data to variable 'b', then *(p+0) data should be go to first like way 1, but the result isn't right. *(p+0) go at last - way 2, show right value.
in easy way to think, i think i was transmit data in direct memory point to point like this
variable a => variable b
[0x000000] => [0x100000]
[0x000001] => [0x100001]
[0x000002] => [0x100002]
... => ...
i don't know why this happen. is anyone can explain about this?
============================================================================
problem was solved. the system was not big endian. i was mistake it.
when i access data by byte unit that first address pointing data shows '65' so i think this system is big endian.
No, it means it is little endian. The least significant byte is in the lowest address and has the value 65.
With respect to 'transmitting' data between pointers of the same type by copying plain-old-data byte by byte, unless you are going between systems then endianness doesn't matter. It only matters in the interpretation, and ( *(p + 0) << 24 ) | ( *(p + 1) << 16 ) | ( *(p + 2) << 8 ) | *(p + 3)
is the big endian interpretation, so gives you the wrong result. You already know that *p
is 65*p
is 65, so even if you forget which way big or little means, *(p + 0) << 24
will be wrong.
If you do want to transmit between systems byte-by-byte, there are the posix functions hton*X*()
and ntoh*X*()
which convert different integral types from host to network or from network to host byte order.