开发者

How to copy primitive type memory in Java?

I have two chars = 4 bytes, that representing integer value (geted from stream).

How can I copy these into a primitive 开发者_运维问答int variable?


You are better off reading 4 bytes as an int from the start. However to turn two char into an int you can use

char ch1, ch2;
int i = (ch1 << 16) + ch2; // or ch2 << 16 + ch1

You need to know whether the order is little or big endian.


Here's one possible way of doing it:

char a = 0x00FF;
char b = 0x0F0F;
int  i = b << 16 | a;

BUT: you'll have to worry about endianness, and about the fact that int is signed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜