开发者

Can we multiply two bytes directly by using * operator directly

I need to perform the followi开发者_如何学Gong operation on a byte (2*x*x)+x where x is a single byte. Can i perform that operation directly as we will do for int. If no how can we perform above operation.


Have you tried the following?

byte x =
int f = 2 * x * x + x;

As an exercise I suggest you print out the results of every possibility byte value and see if you get the expected value. There is only 256 possible byte values.


Yes.

Java integer arithmetic is two-complement; that means that (as long there are enough bits to write down the values) lengthning or shortening the field does not affect the result.

NOTE1: Check for overflows. If the result is not in the 128 / -127 range it will not fit in a byte (or 255 / 0 for unsigned).

NOTE2: Float and double are not part of integer arithmetic.


So apparently you believe that the operator exists because the compiler allows it but you don't believe that the JVM will compute the result correctly. Why?

And how hard is this to test? Bytes only have 256 values each.


There can be two different cases:

byte a = 2; byte b = 2; byte c = a*b it is correct but

byte a = 22; byte b = 22; byte c = a*b it is not correct. because while assigning value to a and b we given value less than 127 but after multiplication the value is longer than one byte that is why we need a bigger datatype to store value of c.

for that case you can use int c = a*b;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜