Reputation: 105
I am trying to convert my integer value to bytes which is to unsigned bytes. I heard that java bytes only provide until 127. Then I tried to reedit my code
This is my code after editing:
Integer servo1 = 5117;
Byte data1;
data1 = (((byte)servo1) >> 6 & (byte)0xFF);
What if I want to add a byte inside a byte array is it possible?
This is the code:
send = {(byte)0xE1, data1, data2, data3};
Now the error is showing Integer cannot be converted to Byte
Can I know how to solve this problem. Thanks
Upvotes: 0
Views: 3674
Reputation: 8652
The error you are getting is **Integer** cannot be converted to **Byte**
. It is because explicit conversion between numerical values cannot be done by their Wrapper classes. By (byte)servo1
you are trying to convert a Integer
i.e. a wrapper class of int into byte
i.e. a primitive type.
Consider the following example :
Long l = 10000000L;
Integer i = (int) l; // Long cannot be converted to int
Byte b = (byte) i; // Integer cannot be converted to byte
To do conversion between wrapper classes you should use methods provided by them :
Long l = 10000000L;
Integer i = l.intValue();
Byte b = i.byteValue();
And to do conversion between primitive primitive type you can do it explicitly as you were trying to do with wrapper classes :
long l = 1000000L;
int i = (int) l;
byte b = (byte) b;
That means your conversion would have worked if you have used primitive types :
int servo1 = 5117;
byte data1;
data1 = (((byte)servo1) >> 6 & (byte)0xFF);
Or if you have used correct method to convert wrapper classes you were using :
Integer servo1 = 5117;
Byte data1;
data1 = (byte)(servo1.byteValue() >> 6 & (byte) 0xFF);
Upvotes: 0
Reputation: 10810
Your syntax is not quite right. You want to cast the whole expression on the right side to byte
if you want to assign it to that variable type. So use this:
Integer servo1 = 5117;
Byte data1;
data1 = (byte) ((servo1) >> 6 & 0xFF);
You may be interested in the Java article on type conversions (specifically the section on integer promotions): https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
Upvotes: 2