Frage

I have an expression:

short w = (short) ((byte) dana) << x);
...
String.format ("%04X", w);

if they includes:

dana = (byte) 0x88; and int x = 5;

I receive 0xF100

instead of 0x1100

What can I do to make it properly!

War es hilfreich?

Lösung

The problem is in the first cast:

(byte) dana

dana is converted to byte, so then when it is later used in expression it needs to be widened back to int and this is done with sign-extension. If number is negative all higher bits are set to 1 to keep its value in 2-complement.

Use bitmask instead:

short w = (short) ((dana & 0xff) << x);

Perhaps it would be even better to avoid using short as well, since java does all arithmetics on int anyway.

Andere Tipps

Check this answer: How to cast from int to byte, then use a bitshift operator

You begin with (extension sign)

  1111 1111 1111 1111 1111 1111 1000 1000

And do the shift

  1111 1111 1111 1111 1111 0001 0000 0000

As you cast to short, you end with

  1111 0001 0000 0000

Which is the result that you get.

The solution is using a wider value (at least short), so it will not be negative. zch's answer is also valid.

You can perform a bitwise and (&) operation to mask the higher bits. For instance:

w &= 0x1fff;

The issue is that when one converts the data to a byte, the sign bit is activated and arithmetic operations are performed instead of logical ones. By using an nd operation, the higher bits are cut off. Or you can postpone conversions and do it as a postprocessing.

One sometimes can also use the arithmetic shifts

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top