【问题标题】:How to print byte in unsign format in Java如何在Java中以无符号格式打印字节
【发布时间】:2011-03-19 17:23:05
【问题描述】:

我需要以无符号格式打印byte 类型的变量。我该怎么做?

【问题讨论】:

  • public static int unsignedToBytes(byte b) { return b & 0xFF; }
  • 您的问题不清楚。请举例说明您想要什么。
  • @Neigyl:把它放在答案中。这样你会得到更多的代表。:)

标签: java int unsigned-integer


【解决方案1】:

我刚刚为你写了那个方法。

public static String printUnsignedByte(byte b){
    StringBuilder sb = new StringBuilder();
    while(b>0){
        sb.insert(0, b%2==0?0:1);
        b>>=1;
    }
    for(int i = 8-sb.length(); i>0; i--){
        sb.insert(0,0);
    }
    return sb.toString();
}

编辑:但它不包括 2 的补码格式。你也需要那个吗? EDIT2:签出:

Integer.toBinaryString(2)

它涵盖了对负值的 2es 补充,但输出太长,它 pribts 4 位。只需用子字符串缩短它就可以了。

编辑 3:我的最终解决方案。

public static String printUnsignedByte(byte b){
    if(b>0){
        StringBuilder ret = new StringBuilder(Integer.toBinaryString(b));
        for(int i = 8-ret.length(); i>0; i--){
            ret.insert(0,0);
        }
        return ret.toString();
    }else{
        return Integer.toBinaryString(b).substring(24);
    }
}

【讨论】:

    【解决方案2】:

    你是说你从一个有符号的 int 开始并且想要绝对值吗?你可以这样做:

        byte b = Byte.parseByte("-9");
        int i = (int) b;
    
        System.out.println(Math.abs(i));
    

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2017-04-09
      • 2012-10-23
      相关资源
      最近更新 更多