假设您有一个数字的二进制或十六进制表示。让我们看看这个:
int number = 0xffffff;
// this would recover the third f, as a stand-alone value, value of third_f would be just f
int third_f = byteSubstring(number,2,1);
// third and fourth f, value of tf would be ff
int tf = byteSubstring(number,2,2);
// all except first, value of except_first would be fffff
int except_first = byteSubstring(number,1,5);
使用单独的按位运算、笔和纸,我知道如何提取所有这些,但将它们组合在一个通用函数中……:)。 JDK 中是否已经提供了可以为数字类型执行此操作的功能?
最佳答案
你有一个 size
和 offset
以位指定。传统上,位从 LSB 开始编号。
您处理 offset
向右移动
result = x >>> offset
您通过 mask 处理尺寸; (1 << size) - 1
是面具
result = result & ((1 << size) - 1)
关于java - Java中的按位运算子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169907/