3
int myInt = 144;
byte myByte = /* Byte conversion of myInt */;

Output should be myByte : 90 (hex value of 144).

So, I did:

byte myByte = (byte)myInt;

I got output of myByte : ffffff90. :(

How can I get rid of those ffffffs?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jyo the Whiff
  • 829
  • 9
  • 23
  • 2
    Why it should be 90? You're not doing hex conversion there. Value 144 is out of `byte` range and will overflow, and hence that value (a negative amount). – Rohit Jain Apr 10 '15 at 05:28
  • 1
    Unfortunately, this is now marked as a duplicate of the wrong question, because the question isn't about how to convert an `int` to a `byte` (despite the incorrect title), but about how to get rid of extra 1 bits when converting the `byte` back to an `int`. Voting to reopen--perhaps it can be closed as a duplicate of a more appropriate question. – ajb Apr 10 '15 at 05:51
  • I am sorry if I am messing this up :), I am a C++ developer and newbie to java, in C++ i know how to do this, int -> unsigned int -> unsigned char, but in JAVA I'm really confused. – Jyo the Whiff Apr 10 '15 at 06:11

2 Answers2

7

byte is a signed type. Its values are in the range -128 to 127; 144 is not in this range. There is no unsigned byte type in Java.

If you are using Java 8, the way to treat this as a value in the range 0 to 255 is to use Byte.toUnsignedInt:

String output = String.format("%x", Byte.toUnsignedInt(myByte));

(I don't know how you formatted the integer for hex output. It doesn't matter.)

Pre-Java 8, the easiest way is

int byteValue = (int)myByte & 0xFF;
String output = String.format("%x", byteValue);

But before you do either of those, make sure you really want to use a byte. Chances are you don't need to. And if you want to represent the value 144, you shouldn't use a byte, if you don't need to. Just use an int.

ajb
  • 31,309
  • 3
  • 58
  • 84
2

Thank you @ajb and @sumit, I used both the answers,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :"+Integer.toHexString(myChar));

o/p,

myChar : 90
Jyo the Whiff
  • 829
  • 9
  • 23