Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte + byte = int... why?

Looking at this C# code:

byte x = 1; byte y = 2; byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte' 

The result of any math performed on byte (or short) types is implicitly cast back to an integer. The solution is to explicitly cast the result back to a byte:

byte z = (byte)(x + y); // this works 

What I am wondering is why? Is it architectural? Philosophical?

We have:

  • int + int = int
  • long + long = long
  • float + float = float
  • double + double = double

So why not:

  • byte + byte = byte
  • short + short = short?

A bit of background: I am performing a long list of calculations on "small numbers" (i.e. < 8) and storing the intermediate results in a large array. Using a byte array (instead of an int array) is faster (because of cache hits). But the extensive byte-casts spread through the code make it that much more unreadable.

like image 742
Robert Cartaino Avatar asked Jun 02 '09 19:06

Robert Cartaino


People also ask

Why do we use int instead of byte?

Performance-wise, an int is faster in almost all cases. The CPU is designed to work efficiently with 32-bit values. Shorter values are complicated to deal with. To read a single byte, say, the CPU has to read the 32-bit block that contains it, and then mask out the upper 24 bits.

Is byte the same as int?

A byte is the format data is stored in memory in past. 8 bits. An int is a format likewise you get it as value from the accumulator.

Can we add byte and int?

The byte data type in Java is a signed integer based on the two's complement 8-bit mechanism. It is different from the int data type that uses 4 bytes (i.e., 32-bit to store a number). The values that can be stored in a single byte are -128 to 127.

Can byte and int be added in Java?

The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).


1 Answers

The third line of your code snippet:

byte z = x + y; 

actually means

byte z = (int) x + (int) y; 

So, there is no + operation on bytes, bytes are first cast to integers and the result of addition of two integers is a (32-bit) integer.

like image 197
azheglov Avatar answered Oct 04 '22 22:10

azheglov