0

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)?

ggrr
  • 7,737
  • 5
  • 31
  • 53
  • A char is a 16bit data type. Why are you using byte? Also, I think your c example conversion is undefined and will have different results for different integer representations. – matt Sep 02 '15 at 07:21
  • 4
    What's up with that weird code? It's just `b = a & 0xFF` – harold Sep 02 '15 at 07:21
  • Note that `unsigned char` isn't guaranteed to be any particular size. – juanchopanza Sep 02 '15 at 07:23
  • @matt, it isn't (in C). [discussion on SO](http://stackoverflow.com/questions/881894/is-char-guaranteed-to-be-exactly-8-bit-long). It is guaranteed to be one byte. It will be 16 bit long, if one byte on your machine is 16 bits long. But it is a weird machine you have. – FreeNickname Sep 02 '15 at 07:32
  • @FreeNickname Sorry, I was refering to java. A [java char](http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.1) is 16 bits. That was my second point though, that the casting that OP is asking about is not uniquely defined. – matt Sep 02 '15 at 07:44
  • In case you missed the implications of my previous comment, it means the conversion is not guaranteed to yield `46`. – juanchopanza Sep 02 '15 at 09:16

3 Answers3

1
int a = -1234;

a = (byte) a & 0xFF;
System.out.println(a); 
//Output: 46
Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22
0

It isn't simulate, it is called casting.

char a = (char)-1234;
byte b = (byte)-1234;
int unsigned = b>=0?b:128 - b;
System.out.println((int)a + ", " + Byte.toUnsignedInt(b) + ", " + unsigned);
//output
//64302, 46, 46
matt
  • 10,892
  • 3
  • 22
  • 34
-1
int a = -1234;
    byte b = a < 0 ? (byte) -((byte) ((a ^ 0xFFFFFFFF) + 1)) : (byte)a;

    System.out.println(b);
Maks
  • 202
  • 1
  • 9
  • 1
    `(a ^ 0xFFFFFFFF) + 1` is a funny way of writing `-a` – harold Sep 02 '15 at 07:24
  • I just wanted to show what exactly hides behind "-" (negative) operation. That's not nice that unsigned primitives are not supported by java – Maks Sep 02 '15 at 07:32