Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中以无符号格式打印字节_Java_Int_Unsigned Integer - Fatal编程技术网

如何在Java中以无符号格式打印字节

如何在Java中以无符号格式打印字节,java,int,unsigned-integer,Java,Int,Unsigned Integer,我需要以无符号格式打印byte类型的变量。我该怎么做?你是说你是从一个带符号的int开始,想要绝对值吗?你可以这样做: byte b = Byte.parseByte("-9"); int i = (int) b; System.out.println(Math.abs(i)); 你是说你是从一个有符号的int开始,想要绝对值吗?你可以这样做: byte b = Byte.parseByte("-9"); int i = (int) b; S

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

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

    byte b = Byte.parseByte("-9");
    int i = (int) b;

    System.out.println(Math.abs(i));

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

    byte b = Byte.parseByte("-9");
    int i = (int) b;

    System.out.println(Math.abs(i));

我刚刚为你写了这个方法

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的补码格式。你也需要吗? 编辑2:签出:

Integer.toBinaryString(2)
它涵盖了2个负值的补充,但输出太长,它优先于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);
    }
}

我刚刚为你写了这个方法

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的补码格式。你也需要吗? 编辑2:签出:

Integer.toBinaryString(2)
它涵盖了2个负值的补充,但输出太长,它优先于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);
    }
}

公共静态int unsignedToBytes(字节b){return b&0xFF;}您的问题不清楚。请举例说明你想要什么。@Neigyl:把它写在答案里。这样您将获得更多的代表性。:)public static int unsignedToBytes(字节b){return b&0xFF;}您的问题不清楚。请举例说明你想要什么。@Neigyl:把它写在答案里。这样你会获得更多的声誉。:)