新学java ,遇到这个问题,于是google 但答案那个是相当多!
  小弟验证了一个正确的
    byte b=(byte)0xab;
int re=b&0x00ff;
        System.out.println(re);

解决方案 »

  1.   

    A hexadecimal numeral consists of the leading ASCII characters 0x or  0X fol-
    lowed by one or more ASCII hexadecimal digits and can represent a positive,zero, or negative integer. Hexadecimal dig its with values 10 through 15 are repre-sented by the ASCII letters  a  through  f  or  A  through  F, respectively; each letter used as a hexadecimal digit may be uppercase or lowercase.When both operands of an operator & ,  ^ , or  |  are of a type that is convertible
    (§5.1.8) to a primitive integral type, binary numeric promotion is first performed
    on the operands (§5.6.2). The type of the bitwise operator expression is the pro-moted type of the operandsWhen an operator applies binary numeric promotion to a pair of operands, each of
    which must denote a value that is convertible to a numeric type, the following
    rules apply, in order, using widening conversion (§5.1.2) to convert operands as
    necessary:
    • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is
    performed. Then:
    • If either operand is of type  double , the other is converted to  double .
    • Otherwise, if either operand is of type float, the other is converted to  float.
    • Otherwise, if either operand is of type long, the other is converted to  long.
    • Otherwise, both operands are converted to type int .
      

  2.   

    以前有人问过这个问题了
    java里只有char是无符号的,所以比char小的类型转成char不会发生问题
    byte,short,int,long等都是有符号的,小类型向大类型转的时候,符号位也被转了,所以要用&运算来过滤高位的1

    byte a = (byte)0xf0;
    int b = (int)a; //直接转,因为符号位也被转了,所以导致结果是负数
    int c = 0xff & a; //把int的byte以上的高位的1都置0,才能保证无符号转换
    小总结
    byte向高位转 (大类型)(byte数据 & 0xff);
    short向高位转 (大类型)(short数据 & 0xffff);
    int向高位转 (大类型)(int数据 & 0xffffffffL); //注意这里有点小陷阱,要用L来表示long型的
      

  3.   

    java 里1 byte = 1/4 int = 1/2 char,而且是有符号的,c里的byte是无符号的所以在java里要用2byte以上的类型来"装"无符号的byteint res = ((byte)0xff & 0xff);
    或者
    int res = (byte)0xff + 256;就可以了。