使用位移位和十六进制代码的 setBit java 方法 - 问题
我无法理解 0xFF7F 的两行及其下面的一行发生了什么。这里有一个链接在某种程度上解释了它。 http://www.herongyang.com/ java/Bit-String-Set-Bit-to-Byte-Array.html 我不知道是否 0xFF7F>>posBit) &旧字节)& 0x00FF 应该是 3 个值“AND”在一起或者应该如何读取。如果有人能更好地澄清这里发生的事情,我将不胜感激。
private static void setBit(byte[] data,
final int pos,
final int val) {
int posByte = pos/8;
int posBit = pos%8;
byte oldByte = data[posByte];
oldByte = (byte) (((0xFF7F>>posBit) & oldByte) & 0x00FF);
byte newByte = (byte) ((val<<(8-(posBit+1))) | oldByte);
data[posByte] = newByte;
}
作为来自 selectBits 方法的参数传入此方法的是 setBit(out,i,val); out = is byte[] out = new byte[numOfBytes]; (在这种情况下 numOfBytes 可以是 7) i = 数字 [57],来自保存 56 个整数的 PC1 int 数组的原始数字。 val = 这是通过 getBit() 方法从字节数组中获取的位。
I am having trouble understanding what is happening in the two lines with the 0xFF7F and the one below it. There is a link here that explains it to some degree.
http://www.herongyang.com/java/Bit-String-Set-Bit-to-Byte-Array.html
I don't know if 0xFF7F>>posBit) & oldByte) & 0x00FF
are supposed to be 3 values 'AND'ed together or how this is supposed to be read. If anyone can clarify what is happening here a little better, I would greatly appreciate it.
private static void setBit(byte[] data,
final int pos,
final int val) {
int posByte = pos/8;
int posBit = pos%8;
byte oldByte = data[posByte];
oldByte = (byte) (((0xFF7F>>posBit) & oldByte) & 0x00FF);
byte newByte = (byte) ((val<<(8-(posBit+1))) | oldByte);
data[posByte] = newByte;
}
passed into this method as parameters from a selectBits method was setBit(out,i,val);
out = is byte[] out = new byte[numOfBytes]; (numOfBytes can be 7 in this situation)
i = which is number [57], the original number from the PC1 int array holding the 56-integers.
val = which is the bit taken from the byte array from the getBit() method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
0xFF7F
是1111 1111 0111 1111
。它右移了根据您作为参数传递的位(即您要设置的位)计算出的位数。如果您指定第三位
posBit = 3 % 8 = 3
,那么该值将与您正在修改的原始字节进行 AND 运算,结果是每个位都保持等于
oldBit
原始位,除了与0
位进行与运算的位,假设您有例如oldByte == 0111 1010
,您将获得:然后该值与
0xFF
只是在进行转换之前丢弃任何不适合字节的位(因为它至少是第九位)。First of all
0xFF7F
is1111 1111 0111 1111
. This is shifted right by an amount of bits calculated from the bit you pass as a parameter (so the one you want to set).If you specify third bit
posBit = 3 % 8 = 3
sothis value is then ANDed with the original byte you are modifying, the result is that every bit is kept equal to
oldBit
original bit except the one that is anded with the0
bit, suppose you have for exampleoldByte == 0111 1010
, you'll obtain:Then the value is anded with
0xFF
just to discard any bit that doesn't fit a byte (because it's at least the ninth bit) before doing the cast.更好的写法是:
A better way to write this would be: