Search code examples
javacintbitwise-operatorsunsigned-char

In Java,how to simulate "converting negative numbers casted by unsigned char in c"?


for example, in c, converting -1234 to unsigned char would become 46:

int main(){
    int a=-1234;
    unsigned char b=a;
    printf("%d\n",b);
    return 0;
};

I want to convert the code to java version, now the code is:

public class Test{
    public static void main(String[] args){
        int a=-1234;
        int b=(a%(Byte.MAX_VALUE-Byte.MIN_VALUE+1))+(a<0?(Byte.MAX_VALUE-Byte.MIN_VALUE+1):0);
        System.out.println(b);
    }
}

Is there any faster (or simpler) way to do this (e.g.:bitwise operation)?


Solution

  • int a = -1234;
    
    a = (byte) a & 0xFF;
    System.out.println(a); 
    //Output: 46