O
O
oventarb2015-04-11 11:51:47
Java
oventarb, 2015-04-11 11:51:47

How to do byte b in Java; b++ and b-- right?

byte b;
How to do:
++b
b++
--b
b--
b+=number
b-=number is two's complement
correct so that the result stays between 0 and 255?
Example: 200 + 100 = 44

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ix_Didicus, 2015-04-13
@oventarb

Unfortunately, there are no unsigned types in Java, but it is possible to apply a bitmask to a value before deriving or using it:

public class bytes{
  public static void main(String[] args){
    byte b = (byte) 200;
    System.out.println(b & 0xFF);
    b+=100;
    System.out.println(b & 0xFF);
  }
}

This code will output 200 and 44.
, an attempt to write to a variable a number greater than allowed by the type of the variable, as a result of which the high bits are simply lost.

E
Evgeny Kornachev, 2015-04-11
@zelan

note: if you need values ​​from 0 to 255, then the byte type is not suitable for you. byte ranges from -128 to 127. As a result, if you need a range from 0 to 255, use short or int, or cast b to int.
The essence of the question is a little unclear: it means that if b=200, you do b += 100 and as a result you want to get 255 (a kind of protection against "overflow")? or something different?

M
mamkaololosha, 2015-04-11
@mamkaololosha

Take the type for the task. Though BigDecimal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question