Here is the problem, I need to do it in Java:
I need to create a byte array with hex values, to send via socket to a device. message format is something like this
STX cmd1 Arg1 , cmd2 ETX Checksum // Any number of commands and arguments
Example :
STX A 1 ETX 148 // 1 and 148 are in decimal STX is 0x02 and ETX is 0x03 , not text STX and ETX.
The byte array which is to be generated for the above example is this :
STX A 1 ETX 148
{(byte)0x2,(byte)0x41,(byte)0x31,(byte)0x3, (byte)0x94}
Can you please help me. How do I do convert these numbers/characters and assign to byte array?
Unless I'm mistaken, you're already heading in the right direction.
A few things to know, an unsigned byte goes from 0 to 255 (0x00 to 0xFF). In Java, there are only signed data types and a byte goes from -128 to +127.
System.out.println(Byte.MIN_VALUE); // -128
System.out.println(Byte.MAX_VALUE); // +127
If fields 3 & 5 are ints casting them to bytes is fine, but know that anything that is over +127 when casted to a byte will overflow into the negative range.
System.out.println((byte)0x94); // -108
System.out.println((byte)148); // -108
If you're wanting the actual positive value of the byte you can AND each byte against 0xFF.
System.out.println(((byte)-108) & 0xFF); // +148
System.out.println(((byte)-1) & 0xFF); // +255
Couldn't you just use what Sotirios Delimanolis proposed in the comments and put your char variables in there?
char a = 'A';
char b = '1';
byte[] buffer = {(byte)0x2, (byte)a, (byte)b, (byte)0x3, (byte)0x94};
Or am I missing something here?
Related
I have int numbers with values between 0-65535. I need to store each number as a byte array of 2 bytes length, whether the number could fit on 1 byte as well or not. Once the numbers are stored in byte arrays, I need to be able to convert them back to int. Right now I don't know how to store a number that is not between -32,768 and 32,767 on 2 bytes and be able to properly convert it back to its original int value.
You can store values from 0-65535 in a char-value and convert a char to byte[] (with a length of 2) using the following method:
public static byte[] toBytes(char c) {
return ByteBuffer.allocate(Character.BYTES).putChar(c).array();
}
See here
EDIT:
Works backwards using ByteBuffer to:
public static char charFromBytes(byte[] bytes) {
return ByteBuffer.wrap(bytes).getChar();
}
Storing the first byte as: (byte) (myIntNumber >> 8) and the second as (byte) myIntNumber seems working just fine for int -> byte array conversion, I'm still curious about how do I get back the int properly from a byte array.
I want to read a binary file and do some manipulation on each byte. I want to test that I am manipulating the bytes correctly. I want to set a byte variable1 to "00000000" and then another byte variable2 set at "00001111" and OR them newvariable = variable1|variable2, shift the newvariable << 4 bits and then print out the int value.
byte a = 00000000;
//Convert first oneByte to 4 bits and then xor with a;
byte b = 00001111;
byte c = (byte)(a|b);
c = c << 4;
System.out.println("byte= " + c + "\n");
I am not sure why I keep getting "incompatiable types:possible lossy conversion from byte to int"
You need to put a '0b' in front of those numbers to express binary constants. The number 00001111 is interpreted as a literal in octal, which is 585 in decimal. The max byte is 127 (since it's signed). Try 0b00001111 instead.
As literals, those will still be int, so depending on where you do the assignment, you may also need to explicitly cast down to byte.
Hi I just encountered with one question of conversion from byte to int.
code was like this
byte b=(byte)-1;
System.out.println(b);
char c=(char) b;
System.out.println(c);
int i=c;
System.out.println(i);
what I understood is when we convert int -1 to byte it will make 8 bit 2's compliment of +1 so value will be like 1111 1111. when we convert that into char based on MSB it will append 1 or 0. and from char to int just widening conversion is there. but I got output like this.
-1
?
65535
I didn't get why it is printing "?" in 2nd place. please help me out on this
based on this array :
final char[] charValue = { 'u', ' ', '}','+' };
i want to print the double value and the ascii value from it in Java.
i can't find a proper solution for that in internet. I just found how to convert a single Character into Integer value. But what about many characters?
the main problem is, i have a large char[] and some double and int values are stored in. for double values they are stored within 4 bytes size and integer 1 or 2 bytes so i have to read all this and convert into double or integer.
Thanks for you help
When java was designed, there was C char being used for binary bytes and text.
Java made a clear separation between binary data (byte[], InputStream/OutputStream) and Unicode text (char, String, Reader/Writer). Hence Java has full Unicode support. The binary data, byte[], need information: their used encoding, in order to be convertable to text: char[]/String.
In Java a char[] will rarely be used (as in C/C++), and it seems byte[] is intended, as you mention 4 elements to be used for an int etcetera. A char is 16 bits, containing UTF-16 text.
For this case one can use a ByteBuffer either wrapping a byte[] or being taken from a memory mapped file.
Writing
ByteBuffer buf = ByteBuffer.allocate(13); // 13 bytes
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
buf.putInt(42); // at 0
buf.putDouble(Math.PI); // at 4
buf.put((byte) '0'); // at 12
buf.putDouble(4, 3.0); // at 4 overwrite PI
byte[] bytes = buf.array();
Reading
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
int a = buf.getInt();
double b = buf.getDouble();
byte c = buf.get();
since I need to control some devices, I need to send some bytes to them. I'm creating those bytes by putting some int values together (and operator), creating a byte and finally attaching it to a String to send it over the radio function to the robot.
Unfortuantely Java has some major issues doing that (unsigned int problem)
Does anybody know, how I can convert an integer e.g.
x = 223;
to an 8-bit character in Java to attach it to a String ?
char = (char)x; // does not work !! 16 bit !! I need 8 bit !
A char is 16-bit in Java. Use a byte if you need an 8-bit datatype.
See How to convert Strings to and from UTF8 byte arrays in Java on how to convert a byte[] to String with UTF-8 encoding.
Sending a java.lang.String over the wire is probably the wrong approach here, since Strings are always 16-bit (since Java was designed for globalization and stuff). If your radio library allows you to pass a byte[] instead of a String, that will allow you to send 8-bit values without needing to worry about converting to UTF8. As far as converting from an int to an unsigned byte, you'll probably want to look at this article.
int to array of bytes
public byte[] intToByteArray(int num){
byte[] intBytes = new byte[4];
intBytes[0] = (byte) (num >>> 24);
intBytes[1] = (byte) (num >>> 16);
intBytes[2] = (byte) (num >>> 8);
intBytes[3] = (byte) num;
return intBytes;
}
note endianness here is big endian.