Java中的按位运算子字符串

Geo*_*Geo 3 java substring bitwise-operators

想象一下,你有一个数字的二进制或十六进制表示.我们来看看:

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);
Run Code Online (Sandbox Code Playgroud)

使用单独的按位操作,笔和纸,我知道如何提取所有这些,但将它们组合在一个通用函数中...... :).JDK中是否有可用于数字类型的东西?

Dou*_*rie 5

你有一个sizeoffset指定位.传统上,这些位从LSB开始编号.

offset通过右移来处理

result = x >>> offset
Run Code Online (Sandbox Code Playgroud)

你通过掩蔽来处理大小; (1 << size) - 1是面具

result = result & ((1 << size) - 1)
Run Code Online (Sandbox Code Playgroud)