我有一个长度为2的字节数组,他们组成一个长度为16位的二进制数,现在如何用Java求出这个16位二进制数的补码?byte []bytes = ...;
byte []finalBytes = fun(bytes); //如何写fun()方法,finalBytes是求补码的函数

解决方案 »

  1.   

    byte [] B = ...
    for(byte a in bytes ){
       byte b = ~a;//取反
       ....//放入B
         
    }
    byte c = B.byteValue();
    c = c+1
      

  2.   

    不明白楼主的意思,计算机中的数字表示就是用的补码呀
    例如,16bit的-1原码表示形式: [1000 0000 0000 0001]
    而计算机内部一直都是补码形式: [1111 1111 1111 1111]
      

  3.   

    我上面理解错了,楼主的意思是指bytes[]里是原码吧,不知道这个是否符合:/**
     * 根据原码获取补码表示, 如-1的16bit原码bytes[]={(byte)0x80,0x01}
     * @param orig 数的原码表示形式,orig[0]是最高8bit.
     * @return 补码表示形式
     */
    public static byte[] fun(byte[] orig) {
       int len = orig.length;
       if (1 == len || 2==len || 4==len || 8==len) {
          if (0x80 == (bytes[0]&0x80)) { //负数的补码才需要变化
             byte[] result = new byte[len];
             int carry = 1;
             for (int i=len-1; i>0; --i) {
             result[i] = (byte)~(orig[i]);
                if (1==carry ) {
                   result[i] = (0xFF==result[i])?0:(byte)(result[i]+1);
                   carry = (0==result[i]) ? 1 : 0;
                }
             }
             result[0] = (byte)((~orig[0] + carry)|0x80);
             return result;
          } else {
             return Arrays.copyOf(bytes, len);
          }
       } else {
          throw new RuntimeException("Unsupported length");
       }
    }
      

  4.   

    上面有些变量没替换过来,重发一遍...public static byte[] GetBytes(byte[] orig) {
    int len = orig.length;
    if (1 == len || 2==len || 4==len || 8==len) {
    if (0x80 == (orig[0]&0x80)) {
    byte[] result = new byte[len];
    int carry = 1;
    for (int i=len-1; i>0; --i) {
    result[i] = (byte)~(orig[i]);
    if (1==carry ) {
    result[i] = (0xFF==result[i])?0:(byte)(result[i]+1);
    carry = (0==result[i]) ? 1 : 0;
    }
    }
    result[0] = (byte)((~orig[0] + carry)|0x80);
    return result;
    } else {
    return Arrays.copyOf(orig, len);
    }
    } else {
    throw new RuntimeException("Unsupported length");
    }
    }
      

  5.   

    请问,
    你加这句话的意思是什么?result[0] = (byte)((~orig[0] + carry)|0x80);
      

  6.   

    for (int i=len-1; i>0; --i) { ... }
    这个循环过程没有处理result[0],它是数字的最高8bit,含有符号位,不能与其他等同处理(否则将错误改变符号位);为了保证这一点,在取反后(符号位变成0了),设置符号位(|0x80的作用)。carry是进位处理。你可以用一些值单步跟踪下: -1{(byte)0x80,0x01} -256{(byte)0x81,0x00} -32767{(byte)0xFF,(byte)0xFF}