Java中子串的按位运算
想象一下您有一个数字的二进制或十六进制表示形式。让我们考虑一下:
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 中是否已经有可用的东西可以对数字类型执行此操作?
Imagine you'd have the binary or hex representation of a number. Let's take this:
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);
Using separate bitwise operations, pen & paper, I know how to extract all of them, but combining them in one generic function ... :). Is there something already available in the JDK that can do this for numeric types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您有一个以位为单位指定的
大小
和偏移
。传统上,这些位是从 LSB 开始编号的。您可以通过右移来处理
偏移
您可以通过屏蔽来处理大小;
(1 << size) - 1
是掩码You have a
size
andoffset
specified in bits. Traditionally the bits are numbered starting at the LSB.You handle the
offset
by shifting rightYou handle the size by masking;
(1 << size) - 1
is the maskJava 有常见的 按位运算符,因此您可以构建一个掩码以及
和
您的数据。编辑
也许一些示例代码会更有用:
当然,您也可以将字符串呈现为十六进制表示形式和子字符串。可能会更快、更易读:)
Java has the usual bitwise operators so you could just build a mask and
and
your data.EDIT
Perhaps some example code will be a bit more usefull:
Of course you could also just render the String to a hex representation and substring that. Might be faster and more readable :)
请参阅 Formatter 中的“format”语法与
String.format("%x", hexa)
结合。例如,String.format("%x", 0xffffff)
返回String
“ffffff”。然后您可以编写您想要的方法作为此方法和 String.substring 的包装器。然而,它不能处理二进制,但手动编码更容易。
编辑:实际上
Integer.toBinaryString
也存在。See the "format" syntax in Formatter and combine with
String.format("%x", hexa)
. For exampleString.format("%x", 0xffffff)
returns theString
"ffffff". Then you can just write the methods you want as wrapper over this andString.substring
.However, it cannot deal with binary, but that's easier to code by hand.
Edit: actually
Integer.toBinaryString
also exists.我不知道标准库中有任何函数可以做到这一点。
类似的东西在
Integer
类中,有一些函数对位进行一些组合操作。你可以自己编码:
I don't know of any functions in the standard library that does that.
Things that are alike are in
Integer
class, there are some functions that do some composed operations on bits.You can code it yourself: