使用0xff安定,需要澄清 [英] Anding with 0xff, clarification needed

查看:77
本文介绍了使用0xff安定,需要澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码片段考虑更换8号线相当于评论

In the following snippet consider replacing line 8 with commented equivalent

1. private static String ipToText(byte[] ip) {
2.  StringBuffer result = new StringBuffer();
3.
4.  for (int i = 0; i < ip.length; i++) {
5.      if (i > 0)
6.          result.append(".");
7.
8.      result.append(ip[i]); // compare with result.append(0xff & ip[i]);
9.  }
10.
11.     return result.toString();
12. }

.equals()测试确认加入 0xFF的不会改变任何东西。有没有要应用这个面具理由吗?

.equals() test confirms that adding 0xff does not change anything. Is there a reason for this mask to be applied?

推荐答案

字节在Java中的&减去一个数,128和127(无符号,就像Java中的每个整数(除了字符如果你想指望它))。通过与安定0xFF的你强迫它是一个积极的 INT 0和255之间。

byte in Java is a number between −128 and 127 (unsigned, like every integer in Java (except for char if you want to count it)). By anding with 0xff you're forcing it to be a positive int between 0 and 255.

它的工作原理,因为Java将执行扩大转换到 INT ,使用符号扩展,所以不是一个消极的字节你将有一个负 INT 。与遮蔽0xFF的将只留下低8位,从而使正数再次(和你最初打算)。

It works because Java will perform a widening conversion to int, using sign extension, so instead of a negative byte you will have a negative int. Masking with 0xff will leave only the lower 8 bits, thus making the number positive again (and what you initially intended).

您可能是因为你有测试没有注意到的差异字节[] 只值小于128。

You probably didn't notice the difference because you tested with a byte[] with only values smaller than 128.

小例子:

public class A {
    public static void main(String[] args) {
        int[] ip = new int[] {192, 168, 101, 23};
        byte[] ipb = new byte[4];
        for (int i =0; i < 4; i++) {
            ipb[i] = (byte)ip[i];
        }

        for (int i =0; i < 4; i++) {
            System.out.println("Byte: " + ipb[i] + ", And: " + (0xff & ipb[i]));
        }
    }
}

这版画

Byte: -64, And: 192
Byte: -88, And: 168
Byte: 101, And: 101
Byte: 23, And: 23

显示之间有什么在字节,什么走进字节时,它仍然是一个 INT 和差异在&放大器的结果是什么; 操作

showing the difference between what's in the byte, what went into the byte when it still was an int and what the result of the & operation is.

这篇关于使用0xff安定,需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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