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
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
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);
Related
I was learning wrapper class, here I learned how to convert int to Interger wrapper class.
But I want to convert int to Byte using Byte wrapper class.
I have tried
int a =10;
Byte c = Byte; //(Not getting suggestion in eclipse)
for example, I know how to convert int to Interger refer code below.
int a =10;
Integer b = Integer.valueOf(a);
You could add an additional cast to the integer like this:
int a = 10;
Byte c = Byte.valueOf((byte)a);
Try it online.
Btw, going from a primitive to an Boxed value is done implicitly by the compiler. So the code above doesn't necessary need the .valueOf:
int a = 10;
Byte c = (byte)a;
Try it online.
But, when you're explicitly casting values, always keep in mind that it can hold unexpected results when doing it wrong. In this case for example, the size of a a byte is smaller than an integer (the range of a byte is [-128, 127] and of an int is [-2147483648, 2147483647]), so something like this wouldn't give the expected result:
int a = 200;
Byte c = Byte.valueOf((byte)a); // Results in -56
Try it online.
This is also the reason why you usually can't go to a smaller type, since it might not fit, but you can go to a larger one without needing the cast:
byte a = 10;
Integer c = Integer.valueOf(a);
Try it online.
int x=30;
Byte c = (byte)x; // Java has auto boxing for wrapper class Byte to byte and opposite automatically
You can cast the same way you normally do with Integer wrapper.
int a =10;
Byte b = Byte.valueOf((byte)a);
//b = 10
An int is 4 bytes. So you can't convert an integer to a byte without losing some data.
int a =1000;
Byte b = Byte.valueOf((byte)a);
//b = -24
You can, however, convert an int to an array of bytes.
Java - Convert int to Byte Array of 4 Bytes?
Same you can do for Byte too:
1. autoboxing
Byte b = (byte) a;
2. valueOf(byte b)
Byte b = Byte.valueOf((byte)a)
Returns a Byte instance representing the specified byte value. If a new Byte instance is not required, this method should generally be used in preference to the constructor Byte(byte), as this method is likely to yield significantly better space and time performance since all byte values are cached.
From JLS 5.0-2. Conversions In Various Contexts so you can't perform 5.1.3. Narrowing Primitive Conversion without cast operator.
// Casting conversion (5.4) of a float literal to
// type int. Without the cast operator, this would
// be a compile-time error, because this is a
// narrowing conversion (5.1.3):
int i = (int)12.5f;
Here are codes,the last second row couldn't compile out cause of the result is int?So,can I
solve that every non integer type in java process as integer in arithmetic?
And I am learning English from all guys,thank you.
byte a=0;
for(int i=0;i<128;i++){
a=(byte)i;
}
byte b=1;
byte c=0;
c=b+a;
System.out.println(b);
Addition operation in java between two shorts or bytes happens after converting both the operands to int and results in an int. So you need to cast your result to byte as it is a lossy conversion. See this
You have to cast a or the result of the addition of a and b to a byte, since a is an integer and it's value might not fit into a byte.
Example:
c = (byte) ((byte) a + b);
or
c = (byte) (a + b);
This way, b gets implicitly converted to an integer, the result is then casted to a byte again.
I have generated a secure random number, and put its value into a byte. Here is my code.
SecureRandom ranGen = new SecureRandom();
byte[] rno = new byte[4];
ranGen.nextBytes(rno);
int i = rno[0].intValue();
But I am getting an error :
byte cannot be dereferenced
Your array is of byte primitives, but you're trying to call a method on them.
You don't need to do anything explicit to convert a byte to an int, just:
int i=rno[0];
...since it's not a downcast.
Note that the default behavior of byte-to-int conversion is to preserve the sign of the value (remember byte is a signed type in Java). So for instance:
byte b1 = -100;
int i1 = b1;
System.out.println(i1); // -100
If you were thinking of the byte as unsigned (156) rather than signed (-100), as of Java 8 there's Byte.toUnsignedInt:
byte b2 = -100; // Or `= (byte)156;`
int = Byte.toUnsignedInt(b2);
System.out.println(i2); // 156
Prior to Java 8, to get the equivalent value in the int you'd need to mask off the sign bits:
byte b2 = -100; // Or `= (byte)156;`
int i2 = (b2 & 0xFF);
System.out.println(i2); // 156
Just for completeness #1: If you did want to use the various methods of Byte for some reason (you don't need to here), you could use a boxing conversion:
Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();
Or the Byte constructor:
Byte b = new Byte(rno[0]);
int i = b.intValue();
But again, you don't need that here.
Just for completeness #2: If it were a downcast (e.g., if you were trying to convert an int to a byte), all you need is a cast:
int i;
byte b;
i = 5;
b = (byte)i;
This assures the compiler that you know it's a downcast, so you don't get the "Possible loss of precision" error.
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
if you want to combine the 4 bytes into a single int you need to do
int i= (rno[0]<<24)&0xff000000|
(rno[1]<<16)&0x00ff0000|
(rno[2]<< 8)&0x0000ff00|
(rno[3]<< 0)&0x000000ff;
I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift
in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together
I also ensure any sign promotion won't affect the result with & 0xff
Primitive data types (such as byte) don't have methods in java, but you can directly do:
int i=rno[0];
Bytes are transparently converted to ints.
Just say
int i= rno[0];
I thought it would be:
byte b = (byte)255;
int i = b &255;
int b = Byte.toUnsignedInt(a);
I'm trying to represent the port number 9876 (or 0x2694 in hex) in a two byte array:
class foo {
public static void main (String args[]) {
byte[] sendData = new byte[1];
sendData[0] = 0x26;
sendData[1] = 0x94;
}
}
But I get a warning about possible loss of precision:
foo.java:5: possible loss of precision
found : int
required: byte
sendData[1] = 0x94;
^
1 error
How can I represent the number 9876 in a two byte array without losing precision?
NOTE: I selected the code by #Björn as the correct answer, but the code by #glowcoder also works well. It's just a different approach to the same problem. Thank you all!
Have you tried casting to a byte ? e.g.
sendData[1] = (byte)0x94;
0x94 is 148 in decimal, which exceeds the range of byte in java (-128 to 127).
You can do one of the following:
1) A cast will work fine because it will preserve the binary representation (no meaningful bits are truncated for 0x00 to 0xFF):
sendData[1] = (byte)0x94;
2) The binary representation of 0x94 as a signed byte is -108 (-0x6C), so the following will have the same effect:
sendData[1] = -0x6C; //or -108 in decimal
Björn gave a good generic answer with using streams. You can also do this same thing using java.nio.ByteBuffer which results in slightly less code and you could also control endianess (byte order) of the output.
To create the byte array:
public static byte[] toByteArray(int bits) {
ByteBuffer buf = ByteBuffer.allocate(4);
buf.putInt(bits);
return buf.array();
}
To reverse it:
public static int fromByteArray(byte[] b) {
ByteBuffer buf = ByteBuffer.wrap(b);
return buf.getInt();
}
My first answer would be bitshifting, but on a second thought I think using outputstreams could be better and more simple to understand. I usually avoid casting, but if you're not going for a generic solution I guess that would be okay. :)
Using streams, a generic solution:
public byte[] intToByteArray(final int i) throws java.io.IOException {
java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
java.io.DataOutputStream d = new java.io.DataOutputStream(b);
d.writeInt(i);
d.flush();
return b.toByteArray();
}
And to reverse it:
public int byteArrayToInt(final byte[] b) throws IOException {
java.io.ByteArrayInputStream ba = new java.io.ByteArrayInputStream(b);
java.io.DataInputStream d = new java.io.DataInputStream(ba);
return d.readInt();
}
You have to cast to (byte) as default number type in java is int, which is bigger than byte. As long as the value fits in byte it is ok to cast.
Try this:
sendData[0] =(byte)0x26
sendData[1] =(byte)0x94
Or this:
sendData[0] =(byte)38
sendData[1] =(byte)148
You must cast data into byte in order to assign it to a byte!
That does not mean you lost precision, just writing 0x26 means an int to Java compiler..
But also note: range of a byte is from -128 to 127, so in case of 0x94=148 it will be represented after byte casting as '-108' , so it will not work correctly in mathematical computations..
It's because everything in Java is signed. 0x94 (148) is greater than Byte.MAX_VALUE(2^7-1).
What you need is
public static byte[] intToByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (b.length - 1 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
I'm working with java.
I have a byte array (8 bits in each position of the array) and what I need to do is to put together 2 of the values of the array and get a value.
I'll try to explain myself better; I'm extracting audio data from a audio file. This data is stored in a byte array. Each audio sample has a size of 16 bits. If the array is:
byte[] audioData;
What I need is to get 1 value from samples audioData[0] and audioData[1] in order to get 1 audio sample.
Can anyone explain me how to do this?
Thanks in advance.
I'm not a Java developer so this could be completely off-base, but have you considered using a ByteBuffer?
Assume the LSB is at data[0]
int val;
val = (((int)data[0]) & 0x00FF) | ((int)data[1]<<8);
As suggested before, Java has classes to help you with this. You can wrap your array with a ByteBuffer and then get an IntBuffer view of it.
ByteBuffer bb = ByteBuffer.wrap(audioData);
// optional: bb.order(ByteOrder.BIG_ENDIAN) or bb.order(ByteOrder.LITTLE_ENDIAN)
IntBuffer ib = bb.asIntBuffer();
int firstInt = ib.get(0);
ByteInputStream b = new ByteInputStream(audioData);
DataInputStream data = new DataInputStream(b);
short value = data.readShort();
The advantage of the above code is that you can keep reading the rest of 'data' in the same way.
A simpler solution for just two values might be:
short value = (short) ((audioData[0]<<8) | (audioData[1] & 0xff));
This simple solution extracts two bytes, and pieces them together with the first byte being the higher order bits and the second byte the lower order bits (this is known as Big-Endian; if your byte array contained Little-Endian data, you would shift the second byte over instead for 16-bit numbers; for Little-Endian 32-bit numbers, you would have to reverse the order of all 4 bytes, because Java's integers follow Big-Endian ordering).
easier way in Java to parse an array of bytes to bits is JBBP usage
class Parsed { #Bin(type = BinType.BIT_ARRAY) byte [] bits;}
final Parsed parsed = JBBPParser.prepare("bit:1 [_] bits;").parse(theByteArray).mapTo(Parsed.class);
the code will place parsed bits of each byte as 8 bytes in the bits array of the Parsed class instance
You can convert to a short (2 bytes) by logical or-ing the two bytes together:
short value = ((short) audioData[0]) | ((short) audioData[1] << 8);
I suggest you take a look at Preon. In Preon, you would be able to say something like this:
class Sample {
#BoundNumber(size="16") // Size of the sample in bits
int value;
}
class AudioFile {
#BoundList(size="...") // Number of samples
Sample[] samples;
}
byte[] buffer = ...;
Codec<AudioFile> codec = Codecs.create(AudioFile.class);
AudioFile audioFile = codec.decode(buffer);
You can do it like this, no libraries or external classes.
byte myByte = (byte) -128;
for(int i = 0 ; i < 8 ; i++) {
boolean val = (myByte & 256) > 0;
myByte = (byte) (myByte << 1);
System.out.print(val ? 1 : 0);
}
System.out.println();
byte myByte = 0x5B;
boolean bits = new boolean[8];
for(int i = 0 ; i < 8 ; i++)
bit[i] = (myByte%2 == 1);
The results is an array of zeros and ones where 1=TRUE and 0=FALSE :)