将字节分成两个较小的数字

时间:2013-07-18 10:51:04

标签: java byte

喜欢主题。我正在编写应用程序,我必须尽可能多地保存RAM。我想将字节分成两部分,每部分4位(数字从0到15) - 如何保存并稍后读取这些值?

2 个答案:

答案 0 :(得分:5)

如果您想要的是在一个字节中存储2个数字(范围0-15),这里有一个关于如何保存和恢复它们的示例。请注意,您必须确保原始数字在允许的范围内,否则这将无效。

    // Store both numbers in one byte
    byte firstNumber = 10;
    byte secondNumber = 15;
    final byte bothNumbers = (byte) ((firstNumber << 4) | secondNumber);

    // Retreive the original numbers
    firstNumber = (byte) ((bothNumbers >> 4) & (byte) 0x0F);
    secondNumber = (byte) (bothNumbers & 0x0F);

另外值得注意的是,如果你想尽可能多地保存内存,你就不应该使用Java 来开始。 JVM已经消耗了内存。母语更适合这种要求。

答案 1 :(得分:2)

您可以获得较低的位

byte lower = b & 0xF; 

更高位

byte higher = (b >> 4) & 0xF; 

并返回一个字节

byte b  = (byte) (lower + (higher << 4));
相关问题