Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# byte data type

Popescu Ion
Ranch Hand

Joined: Jan 14, 2011
Posts: 33
Hi guys,
I was wondering about byte data type. It is 8-bit based, one bit for sign and other 7 for the number itself, therefor maximum 7 bit number is 1111111 = 127, why then byte range is -128 -> 127. How -128 is represented in memory if max possible 7-bit number is 127. Thank You.

Sorry for my English, it is not my first language.
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 567
Popescu Ion wrote:It is 8-bit based, one bit for sign and other 7 for the number itself

Popescu Ion
Ranch Hand

Joined: Jan 14, 2011
Posts: 33

I mean -128 number is represented as 10000000, it needs 8 bit + 1 bit (sign) = 9 bit to represent -128. For the range of -127 -> 127 8-bit it is enough, but beginning with -128 it needs 9 bit. Why ?
Manoj Kumar Jain
Ranch Hand

Joined: Aug 22, 2008
Posts: 191

integers are stored in 2's complement form, and most right bit represents the sign as well as value. So, If you are having value like 1111 1011 then it will be calculated as below.

1111 1011 = -128 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = (-2^7 + 2^6 + ...) = -5

for -128 its stored as 10000000 so the value is calculated as -128.

Do not wait to strike till the iron is hot; but make it hot by striking....
Popescu Ion
Ranch Hand

Joined: Jan 14, 2011
Posts: 33
Manoj Kumar Jain wrote:integers are stored in 2's complement form, and most right bit represents the sign as well as value. So, If you are having value like 1111 1011 then it will be calculated as below.

1111 1011 = -128 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = (-2^7 + 2^6 + ...) = -5

for -128 its stored as 10000000 so the value is calculated as -128.

Now I understand, thank you.
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 13540

6

See Two's complement for more details.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala

I agree. Here's the link: http://aspose.com/file-tools

subject: byte data type