0

so I have an integer that I want to get rid of negative I'm using signed int in c and int in java because they have the same range

java :

     int y = -697451589;
     int test  = ((y  & 0xFFFFFFFF) >> 8 ) 
     System.out.println(test);

Results:

11111111110101100110110110111011 ( -2724421)

In C :

     int y = -697451589;
     int test  = ((y  & 0xFFFFFFFF) >> 8 ) 
     printf("%d" , test);

Results :

110101100110110110111011 ( 14052795)

why in java the result are different? instead of 0xF is to delete the number 1 in front of the integer? why in java does not erase but in C it erases, I try to use long:

 long y = -697451589;
 long test  = ((y  & 0xFFFFFFFFL) >> 8 ); 
 System.out.println(test);

And it works like C, but I want to use int data not long, does anyone know the solution?

Atrs
  • 1
  • 2
  • Because your C int does not have the same range as Java int – user253751 Jul 22 '20 at 12:40
  • 1
    Java has two right-shift operators, `>>` and `>>>`, with different behaviours. – khelwood Jul 22 '20 at 12:40
  • It's very hard to do direct comparison about things like these because what one language might call an `int` may not be the exact thing in another language that also have something called `int`. Different language have different semantics, even though they might share some syntax. – Some programmer dude Jul 22 '20 at 12:40
  • 1
    The C `>>` operator is like the `>>>` operator in Java (unsigned right shift), at least according to http://www.c4learn.com/c-programming/c-bitwise-right-shift/. Actually, according to https://learn.microsoft.com/en-us/cpp/cpp/left-shift-and-right-shift-operators-input-and-output?view=vs-2019#right-shifts, "The result of a right-shift of a signed negative number is implementation-dependent.". – Andy Turner Jul 22 '20 at 12:40
  • 1
    Not certain but I suspect its the way the shift operator works. Try using `>>>` for the java test to shift the sign too. And, at least in java, Anding with `FFFFFFFF` doesn't change the int. – WJS Jul 22 '20 at 12:41
  • 1
    And in C the type `int` is very likely a 32-bit type (unless you're on an older system, or a small embedded system), which means doing a bitwise AND with `0xFFFFFFFF` is kind of useless (as `y & 0xFFFFFFFF` will be equal to `y`). – Some programmer dude Jul 22 '20 at 12:43

0 Answers0