I need to print a variable of type byte in an unsigned format. How do I do that?

有帮助吗?

解决方案

Are you saying you are starting with a signed int and want the absolute value? You could do something like this:

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

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

其他提示

I have just written that method for you.

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();
}

EDIT: But it does not cover 2's complement's format. Do you need that as well? EDIT2: Check out:

Integer.toBinaryString(2)

it covers 2es compliment for negative values, but the output is too long, it pribts 4 bit. Just shorten this with substring and you are done.

Edit 3: My final solution.

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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top