Long to Byte Conversion - java

I have written the following program in Java to convert long to byte.
public class LongtoByte
{
public static void main(String[] args)
{
long a=222;
byte b=(byte)(a & 0xff);
System.out.println("the value of b is" +b);
}
}
The problem is I get the result -34 for the variable b.
Please tell me how to get the correct value. I want the value in bytes only.

Java's types are signed, bytes allow numbers between −128 and +127.this is the reason you were getting −34 for 222 value
long a=121;
byte b=(byte)(a );
System.out.println("the value of b is" +b);

All integer types (including byte) are signed in Java, so if you stick 222 into a Java byte you get an overflow (resulting in the negative number you saw). If you need the range 0–255 for a integral number in Java you'll need at least a short.
However, if you're just going to write that result somewhere as a single byte you don't need to worry, as its bit pattern representation is exactly the same as 222 in an unsigned byte.

You can use the java.lang.Long class' byteValue() method:
byte b = a.byteValue();
You will have to make a Long type object as such:
Long a = new Long(222);
And as others have noted, this will return -34 due to overflow of the range that can be represented by a byte which is 8 bits.

When you print a byte it assumes a range of -128 to 127.
If you print
byte b = (byte) 222;
you should expect to get a negative number.
If you want to store the range 0 to 255 you need to convert it when you get the value out.
int i = 222;
byte[] b = { (byte) i };
int i2 = b[0] & 0xFF; // give me the original unsigned 0 to 255.
assert i == i2;
You can invent all sorts of encoding. e.g. Say you want to store numbers which are only in millions say 0 to 200 million or decimal numbers -1.00 to 1.00 in a byte. You might first think this is impossible because a byte only stores 8 bits.
// store millions.
byte b = (byte) (i / 1000000);
int i = (b & 0xff) * 1000000;
// store decimal from -1.00 to 1.00
byte b = (byte) Math.round(d * 100);
double d = b / 100.0;

public class LongtoByte
{
public static void main(String[] args)
{
long a=222;
byte b=(byte)(a);
System.out.println("the value of b is" +b);
}
}
This byte bValue = (byte) num; statement is converted into a byte format.

Related

Automatic Type Promotion in Java

I understand that the operands are automatically converted to int and we need to cast the expression to byte again. And for byte conversion the 24 bits are truncated and only 8 bits are evaluated. But I am not able to understand this output -56. The final value of e is 200 and converting it in binary gives 11001000. How is the output -56?
public class ByteIntAutomaticPromotionInExpressions {
public static void main(String[] args) {
byte e = 50;
e = (byte)(e *2);
System.out.println(e);
e *= 2;
System.out.println(e);
}
}
OUTPUT:
100
-56
As you can see here:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If the data type was unsigned, 11001000 would be 200 in decimal.
But since it is signed, you treat it like a negative binary number which is -(inverted bits +1) => - (0110111 + 1) = -(0111000) = -56
https://www.allaboutcircuits.com/textbook/digital/chpt-2/negative-binary-numbers/
8 bits, 2^8=256 in this case 200-256 = -56

Java not printing negative binaries right

So, i'm fairly new to java, and i'm a bit confused about the byte system. So I made this program that converts integers to their base two value.
class Bits
{
public static void main(String[] args)
{
byte a;
a = 5;
System.out.println(Integer.toBinaryString(a)); /* prints 101 */
a = -1;
System.out.println(Integer.toBinaryString(a)); /* prints
11111111111111111111111111111111*/
}
}
It works as expected with positive numbers, but when I enter negative numbers, it gets weird. Now I know what two's compliment is, and it doesn't say that -1 is 11111111111111111111111111111111. It is supposed to be 11111111, right? When I change a to an int 255, which would be -1 as a byte, I get the normal result, 11111111, when I switch it to binary. Can someone explain to me why this is happening, or did I do something wrong. (I am using java 8 and i'm on a mac)
Integer.toBinaryString accepts an int as an argument. So a is casted from byte to int before being passed to the method. And yes the two's complement of -1 of a 32 bits integer is 11111111111111111111111111111111.
You should try with Integer.toBinaryString(a & 0xFF). So that a is widened to 32 bits, but then 24 most relevant bits are discarded through masking. The bit sign is kept since you were starting from a byte so the result will be correct.
You can verify it by converting the truncating the int converted from a and the parse it as an int and converting it back to a byte:
int counter = 0;
for (byte a = -128; counter <= 256; ++a, ++counter)
{
byte b = (byte)(Integer.valueOf(Integer.toBinaryString(a & 0xFF), 2) & 0xFF);
System.out.println(a+" == "+b);
}

Correctly convert decimal value to byte value

I need to convert decimal value like
int dec = 129;
into a byte value like
byte frame2 = (byte) 129;
but as you might already have guessed, it converts into an unexpected value. I want the byte value to be literally 129 instead of -127 (value of frame2).
How could you achieve it in Java? I would appreciate an explanation as well.
Thanks
You can't and most likely you don't need to. a byte is -128 to 127 by definition. However you can store any 256 different values in a byte if you want with encoding.
byte b = (byte) 129;
int i = b & 0xff; // == 129
or
byte b = (byte) (129 + Byte.MIN_VALUE);
int i = b - Byte.MIN_VALUE; // also 129.
I need to convert decimal value like
Stop right there. There is no such thing as a 'decimal value'. There are values, which are held in 2s-complement, and there are decimal representations.
int dec = 129;
That will be stored as 129(10), or 81(16).
into a byte value like
byte frame2 = (byte) 129;
The result of that will be -127, because bytes are signed in Java and your value sets the sign bit.
If you want to use the value as though it was 129, use (frame2 & 0xff). However it is quite likely that you don't need to do that at all.
Your question is actually about sign-extension of bytes in Java: it has nothing to do with decimals at all.

How to String-Integer signed value to 2 byte array on the Davik VM?

Given a integer value from a string, I want to convert it to 2 byte signed integer.
BigInteger does the job, but I don't know how to grant 2 bytes...
public void handleThisStringValue(String x, String y){
BigInteger bi_x = new BigInteger(x, 10);
BigInteger bi_y = new BigInteger(y, 10);
byte[] byteX = bi_x.toByteArray();
byte[] byteY = bi_y.toByteArray();
}
I noticed that BigInteger.toByteArray() handles negative values which is suitable for me.
Then I need to read those values (negative and positive ones), or saying convert byte[2] to signed int. Any suggestion?
Well, your questions still lacks certain information.
First, Java integers are 32-bit long, so they will not fit into a 2-byte array, you need a 4-byte array, otherwise you are actually dealing with short data type, which is 16-bit long.
Also, not sure if you need to deal with any kind of byte ordering (little endian, big endian).
At any rate, assuming that you are using integers that only fit in 16-bits and big endian byte ordering, you could do something as follows to create the byte array:
public static byte[] toByteArray(String number){
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(Integer.parseInt(number));
return Arrays.copyOfRange(buffer.array(), 2, 4); //asumming big endian
}
And as follows to convert it back:
public static int toInteger(byte[] payload){
byte[] data = new byte[4];
System.arraycopy(payload, 0, data, 2, 2);
return ByteBuffer.wrap(data).getInt();
}
You can also change the byte order of the ByteBuffer with the ByteBuffer.order method.
I used it as follows:
byte[] payload = toByteArray("255");
int number = toInteger(payload);
System.out.println(number);
Output is 255
int x = bs[0] | ((int)bs[1] << 8);
if (x >= 0x8000) x -= 0x10000;
// Reverse
bs[0] = (byte)(x & 0xFF);
bs[1] = (byte)((x >> 8) & 0xFF);
You can make the inverse:
new BigInteger(byteX);
new BigInteger(byteY);
It's exactly what you want, and then you can use .intvalue() to get it as an int
The solution is simple, based in posts I found here (thank you for all):
Remember that I wanted a 2 byte integer... so it is a Short!
String val= "-32";
short x = Short.parseShort(val);
byte[] byteX = ByteBuffer.allocate(2).putShort(x).array();
... and it works!
Then, I'm using BigInteger to read it back!
int x1 = new BigInteger(byteX).intValue();
or
short x2 = new BigInteger(x).shortValue();

Java: Convert byte to integer

I need to convert 2 byte array ( byte[2] ) to integer value in java. How can I do that?
You can use ByteBuffer for this:
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort();
See also Convert 4 bytes to int.
In Java, Bytes are signed, which means a byte's value can be negative, and when that happens, #MattBall's original solution won't work.
For example, if the binary form of the bytes array are like this:
1000 1101 1000 1101
then myArray[0] is 1000 1101 and myArray[1] is 1000 1101, the decimal value of byte 1000 1101 is -115 instead of 141(= 2^7 + 2^3 + 2^2 + 2^0)
if we use
int result = (myArray[0] << 8) + myArray[1]
the value would be -16191 which is WRONG.
The reason why its wrong is that when we interpret a 2-byte array into integer, all the bytes are
unsigned, so when translating, we should map the signed bytes to unsigned integer:
((myArray[0] & 0xff) << 8) + (myArray[1] & 0xff)
the result is 36237, use a calculator or ByteBuffer to check if its correct(I have done it, and yes, it's correct).
Well, each byte is an integer in the range -128..127, so you need a way to map a pair of integers to a single integer. There are many ways of doing that, depending on what you have encoded in the pair of bytes. The most common will be storing a 16-bit signed integer as a pair of bytes. Converting that back to an integer depends on whether you store it big-endian form:
(byte_array[0]<<8) + (byte_array[1] & 0xff)
or little endian:
(byte_array[1]<<8) + (byte_array[0] & 0xff)
Also, if you can use the Guava library:
Ints.fromByteArray(0, 0, myArray[1], myArray[0]);
It was worth mentioning since a lot of projects use it anyway.
Simply do this:
return new BigInteger(byte[] yourByteArray).intValue();
Works great on Bluetooth command conversions etc. No need to worry about signed vs. unsigned conversion.
import java.io.*;
public class ByteArray {
public static void main(String[] args) throws IOException {
File f=new File("c:/users/sample.txt");
byte[]b={1,2,3,4,5};
ByteArrayInputStream is=new ByteArrayInputStream(b);
int i;
while((i=is.read())!=-1) {
System.out.println((int)i);
FileOutputStream f1=new FileOutputStream(f);
FileOutputStream f2=new FileOutputStream(f);
ByteArrayOutputStream b1=new ByteArrayOutputStream();
b1.write(6545);
b1.writeTo(f1);
b1.writeTo(f2);
b1.close();
}

Categories