简体   繁体   中英

different results in java and c# for right-shift operator

BHere's the code:

c#

private void button1_Click(object sender, EventArgs e)
{
  int a = -33554432;
  byte b = (byte)(a >> 24);
  MessageBox.Show(b.ToString());
}

java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int a = -33554432;
    byte b = (byte)(a >> 24);
    JOptionPane.showMessageDialog(null, Byte.toString(b));
}

I've read around this problem, and I believe there is a relatively simple way of understanding the different behavior, but I need a little help in reaching this understanding. Any takers, please?

Many thanks!

EDIT: ok, now using Byte.toString(). Output for c# = 254 java = -2

Java byte is signed so >> will fill in 1 bits from the left if the number is negative.

C# byte is unsigned so the >> operator is filling in 0 bits.

Either change byte to sbyte in your C# code or use >>> in Java.

Byte in Java is a signed value. In this case you could actually just use:

// Note the triple >
int b = a >>> 24;

Alternatively:

byte b = (byte) (a >> 24);
int c = b & 0xff;

Try to use in Java >>> . This does bit-shifting without taking care of the sign-bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM