7
int val = 233; byte b = (byte) val; System.out.println(b); 

I have a simple case: I have one integer with some value & I want to convert that value into a byte for output. But in this case, a negative value is coming.

How can I successfully place the int value to byte type?

4
  • 1
    Unfortunately bytes in Java are signed. All you can do is try a larger data type or a custom class. Commented Mar 27, 2010 at 15:32
  • @user303218: what's the range of val values? 0-255? Commented Mar 27, 2010 at 15:39
  • @Rahul, why are signed bytes "unfortunate"? Commented Mar 27, 2010 at 18:05
  • 2
    @Steve it is customary to refer to bytes in packed structures (eg, network packet headers) as unsigned, and most other languages have unsigned bytes. In Java, you constantly have to remember yourself that there may or may not be a sign to each byte. Commented Mar 27, 2010 at 19:10

5 Answers 5

16

In Java byte range is -128 to 127. You cannot possibly store the integer 233 in a byte without overflowing.

Sign up to request clarification or add additional context in comments.

1 Comment

Or rather - you can, but you are overflowing the byte.
14

Java's byte is a signed 8-bit numeric type whose range is -128 to 127 (JLS 4.2.1). 233 is outside of this range; the same bit pattern represents -23 instead.

11101001 = 1 + 8 + 32 + 64 + 128 = 233 (int) 1 + 8 + 32 + 64 - 128 = -23 (byte) 

That said, if you insist on storing the first 8 bits of an int in a byte, then byteVariable = (byte) intVariable does it. If you need to cast this back to int, you have to mask any possible sign extension (that is, intVariable = byteVariable & 0xFF;).

Comments

10

You can use 256 values in a byte, the default range is -128 to 127, but it can represent any 256 values with some translation. In your case all you need do is follow the suggestion of masking the bits.

int val =233; byte b = (byte)val; System.out.println(b & 0xFF); // prints 233. 

Comments

5

If you need unsigned value of byte use b&0xFF.

Comments

-1

Since, byte is signed in nature hence it can store -128 to 127 range of values. After typecasting it is allowed to store values even greater than defined range but, cycling of defined range occurs as follows.cycling nature of range

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.