| Author |
demonstrate how to convert step by step 130 to fit in a byte variable
|
pedro abs
Ranch Hand
Joined: Mar 25, 2010
Posts: 33
|
|
someone, please, can demonstrate how the cast is made of the number 130 to fit into a variable of type byte? Step by step ....
I try begin doing this:
130 / 2 = 65
Mod 0
65 / 2 = 32
Mod 1
32 / 2 = 16
Mod 0
16 / 2 = 8
Mod 0
8 / 2 = 4
Mod 0
4 / 2 = 2
Mod 0
2 / 2 = 1
Mod 0
1 / 2 = 0
Mod 1
then 130 = 1000 0010
then....???
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
Welcome to JavaRanch.
I'm not sure exactly what you want to know. The value 130 does not fit into a byte, because a byte is an 8-bit signed data type - it can contain only values between -128 and 127. Values in a byte (as well as in int, short and long) are stored in two's complement format.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Jelle Klap
Bartender
Joined: Mar 10, 2008
Posts: 1409
|
|
It is possible to use a byte to store that bit pattern, but Java will interpret it as a signed two's complement integer, and you'll end up with a negative value: -126.
However, if you know the byte's bit pattern should be interpreted as an unsigned value, you can work around this.
All you need is to widen from a byte to an int and do some bit twiddeling:
I guess the real question is, why would you want to do this?
|
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
|
 |
Nicola Garofalo
Ranch Hand
Joined: Apr 10, 2010
Posts: 308
|
|
As you wrote 130 in binary representation is
1 0 0 0 0 0 1 0
the leftmost bit is set to 1, so the number will be negative
now flip all the bits
0 1 1 1 1 1 0 1
add 1
0 1 1 1 1 1 1 0
in decimal is 126 but remember that the leftmost bit was 1 then the number is negative
= - 126
|
Bye,
Nicola
|
 |
pedro abs
Ranch Hand
Joined: Mar 25, 2010
Posts: 33
|
|
Nicola Garofalo wrote:As you wrote 130 in binary representation is
1 0 0 0 0 0 1 0
the leftmost bit is set to 1, so the number will be negative
now flip all the bits
0 1 1 1 1 1 0 1
add 1
0 1 1 1 1 1 1 0
in decimal is 126 but remember that the leftmost bit was 1 then the number is negative
= - 126
That's what I want to understand.
(why casting 130 to byte results -126)
But why I have to flip all the bits and then add 1?
how this algorithm?
Thanks everybody !!!
|
 |
Nicola Garofalo
Ranch Hand
Joined: Apr 10, 2010
Posts: 308
|
|
That's the two's complement system.
Follow the link that Jesper Young posted in one of the previous messages
I think there you will find all you need to know about it.
http://en.wikipedia.org/wiki/Two's_complement
|
 |
 |
|
|
subject: demonstrate how to convert step by step 130 to fit in a byte variable
|
|
|