Converting Little Endian to Big Endian - java

All,
I have been practicing coding problems online. Currently I am working on a problem statement Problems where we need to convert Big Endian <-> little endian. But I am not able to jot down the steps considering the example given as:
123456789 converts to 365779719
The logic I am considering is :
1 > Get the integer value (Since I am on Windows x86, the input is Little endian)
2 > Generate the hex representation of the same.
3 > Reverse the representation and generate the big endian integer value
But I am obviously missing something here.
Can anyone please guide me. I am coding in Java 1.5

Since a great part of writing software is about reusing existing solutions, the first thing should always be a look into the documentation for your language/library.
reverse = Integer.reverseBytes(x);
I don't know how efficient this function is, but for toggling lots of numbers, a ByteBuffer should offer decent performance.
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
...
int[] myArray = aFountOfIntegers();
ByteBuffer buffer = ByteBuffer.allocate(myArray.length*Integer.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
for (int x:myArray) buffer.putInt(x);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.rewind();
int i=0;
for (int x:myArray) myArray[i++] = buffer.getInt(x);
As eversor pointed out in the comments, ByteBuffer.putInt() is an optional method, and may not be available on all Java implementations.
The DIY Approach
Stacker's answer is pretty neat, but it is possible to improve upon it.
reversed = (i&0xff)<<24 | (i&0xff00)<<8 | (i&0xff0000)>>8 | (i>>24)&0xff;
We can get rid of the parentheses by adapting the bitmasks. E. g., (a & 0xFF)<<8 is equivalent to a<<8 & 0xFF00. The rightmost parentheses were not necessary anyway.
reversed = i<<24 & 0xff000000 | i<<8 & 0xff0000 | i>>8 & 0xff00 | i>>24 & 0xff;
Since the left shift shifts in zero bits, the first mask is redundant. We can get rid of the rightmost mask by using the logical shift operator, which shifts in only zero bits.
reversed = i<<24 | i>>8 & 0xff00 | i<<8 & 0xff0000 | i>>>24;
Operator precedence here, the gritty details on shift operators are in the Java Language Specification

Check this out
int little2big(int i) {
return (i&0xff)<<24 | (i&0xff00)<<8 | (i&0xff0000)>>8 | (i>>24)&0xff;
}

The thing you need to realize is that endian swaps deal with the bytes that represent the integer. So the 4 byte number 27 looks like 0x0000001B. To convert that number, it needs to go to 0x1B000000... With your example, the hex representation of 123456789 is 0x075BCD15 which needs to go to 0x15CD5B07 or in decimal form 365779719.
The function Stacker posted is moving those bytes around by bit shifting them; more specifically, the statement i&0xff takes the lowest byte from i, the << 24 then moves it up 24 bits, so from positions 1-8 to 25-32. So on through each part of the expression.
For example code, take a look at this utility.

Java primitive wrapper classes support byte reversing since 1.5 using reverseBytes method.
Short.reverseBytes(short i)
Integer.reverseBytes(int i)
Long.reverseBytes(long i)
Just a contribution for those who are looking for this answer in 2018.

I think this can also help:
int littleToBig(int i)
{
int b0,b1,b2,b3;
b0 = (i&0x000000ff)>>0;
b1 = (i&0x0000ff00)>>8;
b2 = (i&0x00ff0000)>>16;
b3 = (i&0xff000000)>>24;
return ((b0<<24)|(b1<<16)|(b2<<8)|(b3<<0));
}

Just use the static function (reverseBytes(int i)) in java which is under Integer Wrapper class
Integer i=Integer.reverseBytes(123456789);
System.out.println(i);
output:
365779719

the following method reverses the order of bits in a byte value:
public static byte reverseBitOrder(byte b) {
int converted = 0x00;
converted ^= (b & 0b1000_0000) >> 7;
converted ^= (b & 0b0100_0000) >> 5;
converted ^= (b & 0b0010_0000) >> 3;
converted ^= (b & 0b0001_0000) >> 1;
converted ^= (b & 0b0000_1000) << 1;
converted ^= (b & 0b0000_0100) << 3;
converted ^= (b & 0b0000_0010) << 5;
converted ^= (b & 0b0000_0001) << 7;
return (byte) (converted & 0xFF);
}

Related

Write two integers into high 4bits and lower 4 bits in a byte using java

i have a java code to read a unsigned integer from high 4bit and another from lower 4bit
byte[] value = getBytes(1);
int first = (value[0] & 0xF0) >> 4;
int second = value[0] & 0x0F;
i have to write those 2 integers(first, second) back to new 1 byte using java.
please help me
Basically:
first << 4 | second
(assuming first and second were obtained with the original code, so they are in the range 0x0..0xF).
However, the result of bitwise operations is int for int operands, so this expression is of type int. You need to cast it to byte:
byte b = (byte) (first << 4 | second)

Bitwise operation in ActionScript 3 compare to Java

I am researching this AS3 code that write a BitString into a ByteArray. Source: JPGEncoder#writeBits()
private var byteout:ByteArray;
private var bytenew:int = 0;
private var bytepos:int = 7;
private function writeBits(bs:BitString):void
{
var value:int = bs.val;
var posval:int = bs.len-1;
while (posval >= 0) {
if (value & uint(1 << posval)) {
bytenew |= uint(1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
} else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
But I don't understand part of the code.
What is uint(1 << bytepos)?
What is the if condition if (value & uint(1 << posval))?
I don't know whether the & is "and" bit operator, or "and" condition.
Does if(number) in AS3 means if(number != 0) ?
What is these AS3 code equivalent in Java?
Bitwise operations in Java are somewhat awkward, because Java has no unsigned types.
So when you intend to work with bytes, you should make sure you stay with bytes. Things like 0x0f | 0x80 -> 0b1000 1111 done with bytes must be cast to bytes all the time:
System.out.printf("%x - %x - (byte)%x - (int)%x\n",
(byte)0x80,
(byte)0xf,
(byte)((byte)0x80|(byte)0xf),
(int)((byte)0x80|(byte)0xf));
OUTPUT:
80 - f - (byte)8f - (int)ffffff8f
Having said this, you may want to work with ints from the beginning and cast to bytes later.
The code you present transcribes the BitString into a bit stream cut into bytes.
A special case is handled if all bits of a byte are set, in that case 0xff00 is output.
What is uint(1 << bytepos)?
This moves the lhs of the operator by bytepos bits to the left:
1 << 4 -> 0b00010000
What is the if condition if (value & uint(1 << posval))?
I don't know whether the & is "and" bit operator, or "and" condition.
& is bitwise AND, && is boolean.
The operation is != 0 -> TRUE if the bit at posval position is set. This is the condition to set the corresponding bit in the byte.
Transferring the code to Java should be straightforward actually. I would suggest you use plain int in java and convert to byte just before you write:
byte realByte = (byte)(intbyte & (byte)0xff);
writeByte(realByte);
This way, you avoid constant casting to byte and you avoid the above mentioned problem with negative bytes.
I believe these are the bit shift operators of AS3. You will find that Java uses the same syntax.
This link about bit operations in AS3. The Java documentation page here explains what the operators do.
As for the if condition, it checks if the 'posval'-th bit from the right in value is 1. It "selects" the bit by applying the bitwise and between value and the shifting of value 1 ( 000...01 in binary) by posval bits.

Don't understand how these bitwise operators operate on bytes and integers

I am working with some code that takes in a binary file as input. However, I am having trouble understanding the for loop in the code, as I don't understand what the bitwise operators do to IFD_Address, such as the |=, <<, and & 0xff. I think IFD_Address refers to a pointer in the binary file, but I am not sure. What is this piece of code trying to achieve?
byte[] IFD_Address_tmp = Arrays.copyOfRange(bytes, 4, 8);
int IFD_Address = 0;
int i = 0;
int shiftBy = 0;
for (shiftBy = 0; shiftBy < 32; shiftBy += 8) {
IFD_Address |= ((long) (IFD_Address_tmp[i] & 0xff)) << shiftBy;
i++;
}
This behavior is best understood in terms of moving bits around, not numbers. Bytes comprise eight bits, integers, 32 bits. The loop basically takes each byte in the array and places the corresponding bits in the integer IFD_Address in 8-bit chunks, from right (least significant) to left (most significant), like this:
About the bitwise operations:
& 0xff is required to capture the 8 bits into an integer;
<< shifts the bits to the left to select the appropriate place in IFD_Address;
|= sets the bits in IFD_Address.
See this tutorial for details.

Is there a way to represent int value in byte over 127 without doing bitwise operations?

I am really short on time for doing the learning of bitwise operations.
I want to convert large integer(>127) values without doing '<<' or anything similar.
I need byte representation of integer values used to identify sequence numbers of packets in header sent across UDP. If there is no solution I will introduce two bytes..
Something like: 1, 1 ; 1,2 ; 1,3 ; packet lost ; 1,4 ; packet lost; 2,1 ,2,2
and then reset it upon reaching 127; 127
I can introduce third, but this is rather ugly.
It would be really useful to have black box that is part of java api doing all that byte conversion for me. Is there?
Thanks,
To pack an unsigned 8-bit value into a byte:
static byte toByte(int i) {
if ((i < 0) || (i > 255))
throw new IllegalArgumentException(String.valueOf(i));
return (byte) i;
}
To convert back:
static int toInt(byte b) {
return (b < 0) ? (b + 256) : b;
}
After reading your comments on other answers, it sounds like you might want something like this:
byte[] b = BigInteger.valueOf(counter).toByteArray();
and
long counter = new BigInteger(b).longValue();
Since the length of the array would vary as the counter grows, you'd need some way to indicate its length or delimit it. But this technique will convert any integer value to an array of bytes.
Is the problem that you want unsigned bytes, as in, numbers between 128 and 255 inclusive?
That's...tricky. The Java language won't let you directly treat bytes as unsigned...but with library support it gets a little easier. Guava provides an UnsignedBytes utility class for some of these needs. Addition, multiplication, and subtraction are all exactly the same on signed and unsigned bytes.
EDIT: Judging from your additional comments, you might be interested in Ints.toByteArray(int) and the like, which work on types between byte and BigInteger.
According to my understanding, you want to separate an int into 4 bytes. If so, then just copy paste this code:
int i = /* your int */
int[] b = { (i >> 24) & 0xff, (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff };
Indices 0-3 are each of the 4 bytes in the int.

Change bits value in Byte

I have some data in field type Byte ( I save eight inputs in Byte, every bit is one input ).
How to change just one input in that field ( Byte) but not to lose information about others ( example change seventh bit to one, or change sixth bit to zero )?
To set the seventh bit to 1:
b = (byte) (b | (1 << 6));
To set the sixth bit to zero:
b = (byte) (b & ~(1 << 5));
(The bit positions are effectively 0-based, so that's why the "seventh bit" maps to 1 << 6 instead of 1 << 7.)
Declare b as the primitive type byte:
byte b = ...;
Then you can use the compound assignment operators that combine binary operations and assignment (this doesn't work on Byte):
b |= (1 << bitIndex); // set a bit to 1
b &= ~(1 << bitIndex); // set a bit to 0
Without the assignment operator you would need a cast, because the result of the | and & operations is an int:
b = (byte) (b | (1 << bitIndex));
b = (byte) (b & ~(1 << bitIndex));
The cast is implicit in the compound assignment operators, see the Java Language Specification.
To set a bit use :
public final static byte setBit(byte _byte,int bitPosition,boolean bitValue)
{
if (bitValue)
return (byte) (_byte | (1 << bitPosition));
return (byte) (_byte & ~(1 << bitPosition));
}
To get a bit value use :
public final static Boolean getBit(byte _byte, int bitPosition)
{
return (_byte & (1 << bitPosition)) != 0;
}
Note that the "Byte" wrapper class is immutable, and you will need to work with "byte".
You really owe it to yourself to look into masking functions for and, or, and xor -- they allow you to simultaneously verify, validate, or change... one, some, or all of the bits in a byte structure in a single statement.
I'm not a java programmer by trade, but it's derived from C and a quick search online seemed to reveal support for those bitwise operations.
See this Wikipedia article for more information about this technique.

Categories