将字节分成两个较小的数字 [英] Divide byte into two smaller numbers

查看:106
本文介绍了将字节分成两个较小的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与主题类似。我在编写应用程序时必须节省尽可能多的RAM。我想将字节分成两个部分,每个部分4位(数字从0到15)-如何保存并以后读取该值?

Like in topic. I am writing application where I must save as much RAM as possible. I want to split byte into two parts 4 bits each (numbers from 0 to 15) - how can I save and later read this values?

推荐答案

如果要在一个字节中存储2个数字(范围为0-15),下面是有关如何保存和恢复它们的示例。请注意,您必须确保原始数字在允许的范围内,否则将不起作用。

If what you want is store 2 numbers (range 0-15) in one byte, here's an example on how to save and restore them. Note that you have to make sure your original numbers are within the allowed range, otherwise this will not work.

    // 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已经自行消耗内存。母语更适合此要求。

Also worth noting that if you want to save as much memory as possible you shouldn't be using Java to start with. JVM already consumes memory by itself. Native languages are much more suited to this requirement.

这篇关于将字节分成两个较小的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆