Forums Register Login

Java Bytes

+Pie Number of slices to send: Send
Hi everyone,

Consider the below program



Now from what i understand 1 byte is 8 bits so the maximum is all 1's (ie. 255).

The above first function ByteTest1 i cast the hexadecimal a byte as so



Now why do i have to cast it even when 0x9C is well below 255 but if i do not cast it the compiler complains saying that it is an integer.

The above second function ByteTest2 i did not cast the hexadecimal a byte as so



Now why is it that the compiler accepts the hexadecimal value 0x5A without any casting but for 0x9C the compiler emit errors saying it is an integer?

Am i missing something?

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West
+Pie Number of slices to send: Send
Your missing that Byte are signed : (8 bits, all 1 is -1 !)

So byte range is -128 -> 127
+Pie Number of slices to send: Send
In other words, the maximum value you can store in a byte is 127, NOT 255.

Layne
+Pie Number of slices to send: Send
Hi everyone,

In that case let's say if i have the number -8 and +10.
How do i convert them to signed bytes respectively?

Richard West
[ October 14, 2005: Message edited by: West Richard ]
+Pie Number of slices to send: Send
Richard,

Please check your private messages.
+Pie Number of slices to send: Send
+Pie Number of slices to send: Send
 

Originally posted by West Richard:
Hi everyone,

In that case let's say if i have the number -8 and +10.
How do i convert them to signed bytes respectively?

Richard West

[ October 14, 2005: Message edited by: West Richard ]



Even better than the above, you can just do this:

This works because these numbers are in the range of valid values for bytes. Also, they are already *signed*.

Perhaps you meant "unsigned" instead. If so, assigning these values to variables is the same, assuming you are actually interested in the bit pattern of the value -8, for instance. Once you do the assignment, you just treat the variable as if its unsigned. You can do any bit-wise operations you wish, as long as you cast the result back to a byte. (The result of &, |, ^, >>, and << is promoted to an int for some reason.)

I hope this answers your question. If not, perhaps you can illustrate what you are trying to do with some more specific code.

Layne
Getting married means "We're in love, so let's tell the police!" - and invite this tiny ad to the wedding:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1453 times.
Similar Threads
here is my doubt about Integer literal.... help
No unsigned data
casting an int to a byte in the return statement
KM question (write method)
(Solved!) Boxing tricks
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 07:43:39.