How to follow C++ bit storage in Java?
if I have in c++:
char abc[4];
abc[0] = 0xC0; //11000000 in binary
abc[1] = 0x20; //00100000 in binary
abc[2] = 0x44; 开发者_如何学Go//01000100 in binary
abc[3] = 0x20; //00100000 in binary
So how this will be stored in memory -
11000000 00100000 01000100 00100000 or the reverse way ??
-----------------------------------
0th 1st 2nd 3rd
In Java I am creating Bitset abc = new Bitset(32);
So I need to store the same values in this(same order).This may be modified later according to bit positions so have to be exact same way.
So abc[32] = 0xC0204420
will do? And if I want to store
the values in c++ way what to do??
If I am wrong then how to do this in Java...
Endian is not an issue. If you use char[4]
the lowest address 0 will be first, the highest 3 will be last, so you get in memory
char[0] char[1] char[2] char[3]
whatever you do.
If you do a int x = *(reinterpret_cast<int*>(abc))
, then you get different results, depending on endianness, because the (4byte-) int
is sometimes read as 0123
, sometimes 3210
-- and I think even 2301
has been around in the 60s.
You can not put 0xC0204420
(a larger number then 127
) into the [32]
ths position of abc
. If you want to implement something "fast" (and dangerous) you would need a platform-depending reinterpret_cast
. Take a look at hton
and ntoh
.
Yes, that will be how C++ represents the char
array in memory.
As for the Java, it's completely arbitrary. It depends on how you define the mapping between the index into your Bitset
and the byte/bit index in the C++ "representation". You can define this mapping any way you like, so long as you're consistent.
If you create char abc[4];
and fill it character by character, then yes, in memory it will be represented as 11000000 00100000 01000100 00100000
.
The problem I see with Java BitSet is that the contents of a BitSet cannot be represented simple as a number - there is no method for it, so how would you convert 0xC0204420 to a BitSet or how would you represent a BitSet as a number like 0xC0204420? One possibility is to take every eight bits from a BitSet, make a char
from them (using Java bitwise operators like <<
and |
) and then create some char array or something from them that should be equal to the earlier C++ char[4]
.
精彩评论