喜欢在主题中.我正在编写应用程序,我必须尽可能多地保存RAM.我想将字节分成两部分,每部分4位(数字从0到15) - 如何保存并稍后读取这些值?
如果您想要的是在一个字节中存储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);
Run Code Online (Sandbox Code Playgroud)
另外值得注意的是,如果你想节省尽可能多的内存,你不应该使用Java开始.JVM已经消耗了内存.母语更适合这种要求.