문제

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