开发者

How to copy primitive type memory in Java?

开发者 https://www.devze.com 2023-04-04 11:50 出处:网络
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 th

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

精彩评论

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