1

I want to know how can i convert an integer to byte theoretically. I mean i don't want to use a predefined program but i want just to know how can i implement it. What i know that from -128 to 127 an integer is the same as byte but the problemes is from 128 to 128 to +infinite and from -129 to -infinite. For example given the following code:

    Integer a = 140;//10001100 this is his binary conversion
    Byte zz = (byte) a.byteValue();
    System.out.println(zz);// result is -116

How that conversion works in java? Thanks in advance

BenMansourNizar
  • 1,558
  • 4
  • 21
  • 42

4 Answers4

3

That value is out of range of the Byte and hence overflows.

Refer JLS 4.2.1:

The values of the integral types are integers in the following ranges:

  1. For byte, from -128 to 127, inclusive

A byte is 8 bits , the most significant bit specifies the sign of the number and are are encoded in two's complement.

Read this wonderful SO answer for more.

Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

Byte value binary representation will not change, it will still be 10001100 but it will be interpreted differently, since byte is a signed type in two's complement representation http://en.wikipedia.org/wiki/Twos_complement and since bit 7 is set it means that now it's a negative number -116

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

when you are narrowing a primitive, you must explicitly make a cast - so you acknowledge a possible loss of data.

There is no loss if value is within the -128...127 byte value range

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

You can not convert value grate than 127 into byte as it do not have place to store it. As 140 in binary is 10001100 it mean that you need a type that store at lest 8 bits. A byte store 8 bits but one of then is reserved for sign. So you can not fit it into it. You can use short witch store 16 bits (15 and 1 for sign).

The zero in different types expressed in binary;

byte  b = 0b000_0000;
short s = 0b000_0000_0000_0000;
int   i = 0b000_0000_0000_0000_0000_0000_0000_0000;

If you try to declare something like:

byte  b = 0b1000_1100;

The compiler will tall you Type mismatch: cannot convert from int to byte.