-2

I have this integer in java:

int i = 1067030938;
byte b = (byte) i;

which gives me:

-102

How could I go from b back to i ?


I tried :

b = b & 0xff;

but this gives 154

fuggerjaki61
  • 822
  • 1
  • 11
  • 24
hispanicprogrammer
  • 367
  • 3
  • 6
  • 22
  • 2
    Does this answer your question? [Converting from byte to int in java](https://stackoverflow.com/questions/9581530/converting-from-byte-to-int-in-java) – fuggerjaki61 Jun 19 '20 at 17:03
  • @fuggerjaki61 hey thanks for the link, I checked it before :) If you see I am using `b & 0xff` (solution suggested there as well) but for some reason it doesnt work. Also I am using java 11 and for some reasone `int i = Byte.intValue();` doesnt come as an option. Let me know tho, if you think I am using something wrong! Piece – hispanicprogrammer Jun 19 '20 at 17:05
  • 3
    The int value (1067030938) is far outside the range (-128 to 127) of the byte type. What are you trying to achieve here? – vsfDawg Jun 19 '20 at 17:10
  • i don't really understand what you're trying to archieve with this. casting `(int) b` returns `-102`. What output do you expect? – fuggerjaki61 Jun 19 '20 at 17:12
  • @fuggerjaki61 hey as stated in my question I try to from byte back to int. That means I want to go from `-102` to `1067030938` – hispanicprogrammer Jun 19 '20 at 17:17
  • 2
    @hispanicprogrammer You were already told several times that this is not possible! – Seelenvirtuose Jun 19 '20 at 17:18

1 Answers1

2

If you have

int i = 1067030938;

And just want the low order 8 bits, then do

i &= 0xff;

System.out.println(i);

Prints

154

If you want the signed value of converted int then do this

i = (byte)i; // will be -102
WJS
  • 36,363
  • 4
  • 24
  • 39