开发者

What's the best way in Java to calculate a partial decimal value from parts of a 32-bit value

开发者 https://www.devze.com 2023-02-03 16:46 出处:网络
I have a 32-bit integer value and I want to translate that into two decimal values. One value from the 5 least sign开发者_Python百科ificant bits and one decimal value from the rest of the bits (27 bit

I have a 32-bit integer value and I want to translate that into two decimal values. One value from the 5 least sign开发者_Python百科ificant bits and one decimal value from the rest of the bits (27 bits).

How would I do that in Java?

The only solution I can think of is something like this:

int i = 1073326082;

String binaryString = Integer.toBinaryString(i);

int fiveLeastSigValue = Integer.parseInt(binaryString.substring(27), 2));

int theRest = Integer.parseInt(binaryString.substring(0, 27), 2));

But im sure there is some more efficient way to do this. Any ideas?


Well, I'd imagine:

int value = ...;
int leastSignificant = value & 0x1f; // Bottom 5 bits
int mostSignificant = value >> 5; // Top 27 bits

Adjust the shift operator to ">>>" if you want to 0-extend (i.e. always have positive values).

I'm not sure what you mean by "partial decimal value" though - "decimal" is usually used to refer to non-integers, but you're parsing integers. Is this what you want?

0

精彩评论

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