How do you append two bytes to an int - java

I'm trying to append two bytes that have hex values and store them into an integer. So obviously everything will be unsigned values.
I'll provide an example since that is much easier to see.
two bytes
0x20 0x07
Integer
Edit: Oops I made a huge mistake here. Sorry for all the confusion.
I want integer to store 2007 not 0x2007. I'm really sorry about that.
Is there way to do this without converting the byte to String and append and switch to int?
or is converting to String is the only way?

You can try
byte b1 = (byte) 0x90;
byte b2 = (byte) 0xF7;
int i = ((b1 & 0xFF) << 8) | (b2 & 0xFF);
However if you are using DataInputStream or ByteBuffers you usually don't need to do this. Just use getShort in both cases.

Yes, just shift b1 by 8 bits and add it to b2:
byte b1 = 0x20;
byte b2 = 0x07;
int i1 = (b1 << 8) + b2; // gives 0x2007
// alternatively
int sameInt = b1 * 256 + b2; // gives 0x2007

Related

How to simplify this binary-to-java-type code?

I get two java bytes as input that together symbolizes a 16-bit signed integer. I need to convert it to one single java integer (signed, of course). I have come up with a "ugly" solution, that includes converting to an int, then to a short and then back to an int. Is there a shorter and more elegant way?
My code is as following:
public int convert(byte b1, byte b2){
int i1 = (int) (((b2 << 8) + (b1 & 0xFF)) & 0x0000FFFF);
short s1 = (short) i1;
int i2 = (int) s1;
return i2;
}
This seems to match your converter - not certain it is simpler but it is certainly less verbose.
public int convert2(byte b1, byte b2) {
return new BigInteger(new byte[]{b2,b1}).intValue();
}
The following is equivalent:
return (short) ((b2 << 8) | (b1 & 0xFF));
byte has a small enough range that it is practical to test this equivalence for all possible values of b1 and b2:
byte b1 = Byte.MIN_VALUE;
do {
byte b2 = Byte.MIN_VALUE;
do {
assertEquals(convert(b1, b2), convertEquivalent(b1, b2));
} while (b2++ != Byte.MAX_VALUE);
} while (b1++ != Byte.MAX_VALUE);
Ideone demo
#AndTurner is probably the solution you sought.
However if a byte array or some file channel (memory mapped file), input stream is involved, one may use a ByteBuffer.
byte[] bytes = ...
ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
...
short n = buf.readShort(); // Sequential
short m = buf.readShort(354L); // Direct access

Convert char[] to byte[] without losing 'bits'

I'm developing an Android 2.3.3 application with Java.
This app is an iOS code with unsigned data types port to Java.
On iOS it works with UInt16 and UInt8. In one case instead using byte[] I'm using char[].
But know I have to send that char[] as a byte[] using a DatagramPacket.
If one element of char[] is 128, how can I do to insert into byte[] and the receiver gets 128. I don't know what happens if I do this:
char c = (char)128;
byte b = (byte)c;
Which will be b value?
128 = 10000000. b = -1 or b = 127?
How can I convert char[] to byte[] without losing any bits?
In Java char is an unsigned 16-bit quantity. So you can directly convert your uint16 to char without doing anything else.
For unsigned 8-bit quantity you have 2 options:
Use byte. It also holds 8 bits. You don't lose any bits just because it is signed. However, if you do arithmetic with it you need to remember that Java will scale byte up automatically to an int and sign-extend it. To prevent this just always mask it like this:
byte b;
int foo = 5 * (b & 0xFF);
Use char. It is unsigned and can hold 16 bits so the 8 bits will fit in there quite nicely. To put a byte into a char just do this:
byte b;
char c = (char)(b & 0xFF); // Mask off the low-order 8 bits
To put a char into a byte just do:
char c;
byte b = (byte)c; // Truncates to 8 bits
Be aware that byte in Java is signed, so that whenever you do arithmetic with it you need to mask the low-order 8 bits only (to prevent sign-extension). Like this:
byte b;
int foo = (b & 0xFF);
You can do all the normal bitwise operations you want with a byte without having to mask:
byte b;
if (b & 0x80) ... // Test a flag
b |= 0x40; // Set a flag
b ^= 0x20; // Flip a flag from 0 to 1 or 1 to 0
b ^= ~0x10; // Clear a flag
byte x = b << 3; // Shift left 3 bits and assign
byte x = b >>> 4; // Shift right 4 bits and assign (WITHOUT sign extension)
I think you need to rethink your approach so you don't end up needing to convert char[] to byte[].
If your data really is characters, then you want to look at various serialization techniques, such as using new String(char[]) to create a string and then using getBytes(Charset) to get the bytes as encoded by a given Charset (because, of course, the same characters result in different bytes when encoded in ASCII or UTF-8 or UTF-16, etc.).
But from your question, it sounds like you're not really using characters, you're just using char as a 16-bit type. If so, doing the conversion isn't difficult, something along these lines:
byte[] toBytes(char[] chars) {
byte[] bytes = new byte[chars.length * 2];
int ci, bi;
char ch;
bi = 0;
for (ci = 0; ci < chars.length; ++ci) {
ch = chars[ci];
bytes[bi++] = (byte)((ch & 0xFF00) >> 8);
bytes[bi++] = (byte)(ch & 0x00FF);
}
return bytes;
}
Reverse the masks if you want the result to be small-endian instead.
But again, I would look at your overall approach and try to avoid this.

short to byte and byte to short conversion in Android

I am developing a software in Android. In a particular portion of software, I need to convert short to byte and re-convert to it to short. I tried below code but values are not same after conversion.
short n, n1;
byte b1, b2;
n = 1200;
// short to bytes conversion
b1 = (byte)(n & 0x00ff);
b2 = (byte)((n >> 8) & 0x00ff);
// bytes to short conversion
short n1 = (short)((short)(b1) | (short)(b2 << 8));
after executing the code values of n and n1 are not same. Why?
I did not get Grahams solution to work. This, however do work:
n1 = (short)((b1 & 0xFF) | b2<<8);
You can use a ByteBuffer:
final ByteBuffer buf = ByteBuffer.allocate(2);
buf.put(shortValue);
buf.position(0);
// Read back bytes
final byte b1 = buf.get();
final byte b2 = buf.get();
// Put them back...
buf.position(0);
buf.put(b1);
buf.put(b2);
// ... Read back a short
buf.position(0);
final short newShort = buf.getShort();
edit: fixed API usage. Gah.

Java: Bytes to floats / ints

I have a byte array sent via UDP from x-plane. The bytes (4) are all floats or integers…
I tried to cast them to floats but no luck so far…
Example array:
byte data[41] = {-66,30,73,0};
How do I convert 4 bytes into int or float and doesn't float use 8 bytes?
Note: I recommend #Ophidian's ByteBuffer approach below, it's much cleaner than this. However this answer can be helpful in understanding the bit arithmetic going on.
I don't know the endianness of your data. You basically need to get the bytes into an int type depending on the order of the bytes, e.g.:
int asInt = (bytes[0] & 0xFF)
| ((bytes[1] & 0xFF) << 8)
| ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
Then you can transform to a float using this:
float asFloat = Float.intBitsToFloat(asInt);
This is basically what DataInputStream does under the covers, but it assumes your bytes are in a certain order.
Edit - On Bitwise OR
The OP asked for clarification on what bitwise OR does in this case. While this is a larger topic that might be better researched independently, I'll give a quick brief. Or (|) is a bitwise operator whose result is the set of bits by individually or-ing each bit from the two operands.
E.g. (in binary)
10100000
| 10001100
-----------
10101100
When I suggest using it above, it involves shifting each byte into a unique position in the int. So if you had the bytes {0x01, 0x02, 0x03, 0x04}, which in binary is {00000001, 00000010, 00000011, 00000100}, you have this:
0000 0001 (1)
0000 0010 (2 << 8)
0000 0011 (3 << 16)
| 0000 0100 (4 << 24)
--------------------------------------------------------
0000 0100 0000 0011 0000 0010 0000 0001 (67 305 985)
When you OR two numbers together and you know that no two corresponding bits are set in both (as is the case here), bitwise OR is the same as addition.
See Also
Wikipedia: Bitwise OR
You probably want to make use of java.nio.ByteBuffer. It has a lot of handy methods for pulling different types out of a byte array and should also handle most issues of endianness for you (including switching the byte order if necessary).
byte[] data = new byte[36];
//... populate byte array...
ByteBuffer buffer = ByteBuffer.wrap(data);
int first = buffer.getInt();
float second = buffer.getFloat();
It also has fancy features for converting your byte array to an int array (via an IntBuffer from the asIntBuffer() method) or float array (via a FloatBuffer from the asFloatBuffer() method) if you know that the input is really all of one type.
Use a DataInputStream as follows:
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
float f = dis.readFloat();
//or if it's an int:
int i = dis.readInt();
You cannot just cast them into a float/int. You have to convert the bytes into an int or float.
Here is one simple way to do it:
byte [] data = new byte[] {1,2,3,4};
ByteBuffer b = ByteBuffer.wrap(data);
System.out.println(b.getInt());
System.out.println(b.getFloat());
There is a reasonable discussion here:
http://www.velocityreviews.com/forums/t129791-convert-a-byte-array-to-a-float.html
In my opinion the ByteBuffer approach is better, you can specify where the data is wrapped (from which byte index, here 0) and also the endianness (here BIG_ENDIAN).
try {
float result = ByteBuffer.wrap(data, 0, 4).order(BIG_ENDIAN).getFloat();
} catch (IndexOutOfBoundsException exception) {
// TODO: handle exception
}
Functions similar to getFloat() exist for Int, Short, Long...

Read structured data from binary file -?

I know the file structure, suppose this structure is this:
[3-bytes long int],[1-byte long unsigned integer],[4-bytes long unsigned integer]
So the file contains chains of such records.
What is the most elegent way to parse such a file in Java?
Supposedly, we can define a byte[] array of overall length and read it with InputStream, but how then convert its subelements into correct integer values?
First thing, byte value in java is signed, we need unsigned value in our case.
Next thing, are there useful methods that allow to convert a sub-array of bytes, say, bytes from 1-st to 4-th into a correct integer value?
I know for sure, there are functions pack & unpack in Perl, that allow you to represent a string of bytes as an expression, let's say "VV" means 2 unsigned long int values. You define such a string and provide it as an argument to a pack or unpack functions, along with the bytes to be packed/unpacked. Are there such things in Java / Apache libs etc ?
Like #Bryan Kyle example but shorter. I like shorter, but that doesn't mean clearer, you decide. ;) Note: readByte() is signed and will have unexpected results if not masked with 0xFF.
DataInputStream dis = ...
// assuming BIG_ENDIAN format
int a = dis.read() << 16 | dis.read() << 8 | dis.read();
short b = (short) dis.read();
long c = dis.readInt() & 0xFFFFFFFFL;
or
ByteBuffer bb =
bb.position(a_random_postion);
int a = (bb.get() & 0xFF) << 16 | (bb.get() & 0xFF) << 8 | (bb.get() & 0xFF);
short b = (short) (bb.get() & 0xFF);
long c = bb.readInt() & 0xFFFFFFFFL;
You may take a look at this sample BinaryReader class which is based on the DataInputStream class.
You should be able to do this using a DataInputStream. It's been a while since I've done much development like this, but the trick I seem to remember is that if there's an impedance mis-match between your input format and the language's data types you'll need to construct the data byte by byte. In this case, it looks like you'll need to do that because the data structure has oddly sized structures.
To give you an example to read the first record you might need to do something like this (I'm using a, b, and c for the attributes of the record)
DataInputStream dis = ...
int a = 0;
a = dis.readByte();
a = a << 8;
a = a | dis.readByte();
a = a << 8;
a = a | dis.readByte();
short b = 0;
b = dis.readByte();
long c = 0;
c = dis.readByte();
c = c << 8;
c = c | dis.readByte();
c = c << 8;
c = c | dis.readByte();
c = c << 8;
c = c | dis.readByte();
Obviously, this code could be tightened up by compounding some of the statements, but you get the general idea. What you might notice is that for each of the attributes being read I have to use a primitive that's larger than needed so there aren't any overflow errors. For reference, in Java:
byte = 1 byte
short = 16 bit, 2 bytes
int = 32 bits, 4 bytes
long = 64 bits, 8 bytes

Categories