Flipping Hexadecimal Values

Dark Void

Mitglied
Hi,
I need to write a Java program that takes a user input (integer), converts that to hexadecimal, flipps the value and outputs the result.

Flipping goes like this:

00037B54 -> 547B0300

(Last byte comes first, pre-last byte comes second, second byte comes second and first byte comes last).

Java:
import javax.swing.JOptionPane;

public class ValueFlipping 
{
	public static void main(String[] args) 
	{
		String input = JOptionPane.showInputDialog("Please enter a number with up to 9 digits:");
		
                try 
		{
			int number = Integer.parseInt(input);	
			String hexString = Integer.toHexString(number);
			
			// TODO 8 digited output & flipping
			
			JOptionPane.showMessageDialog(null, "Result: "+hexString);
		} 
		
		catch (Exception e) 
		{
			JOptionPane.showMessageDialog(null, "Invalid input!");
		}
}
I´m still missing the part where it flipps the value. The HEX output should always format to have 8 digits -> 00000063 (when 99 is entered) to make flipping easier.

I would use hexString.charAt(_); to talk to each position in the HEX number. It should store the result to a new array because otherwise it would overwrite the value from where it reads from.

Thanks for any tips.
 
Zuletzt bearbeitet:

HelgeW

Mitglied
Hi,

Have a look at String.format() to make your output string 8 char long.
and after it is ease to flip the string, isn't it?!

Hope it helps,
Helge
 

Ullenboom

Bekanntes Mitglied
U want to do a big endian <-> little endian encoding. Java has almost no support for this with one exception: with bytebuffers. It will look like this:

Java:
int i = Integer.parseInt( "37B54", 16 );
BigInteger bi = new BigInteger( ByteBuffer.allocate(4).order( ByteOrder.LITTLE_ENDIAN ).putInt( i ).array() );
System.out.printf( "%X", bi );
 
N

nillehammer

Gast
Integer.reverseBytes is the way to go:
Java:
int number = Integer.parseInt(input);   
int reversedBytes = Integer.reverseBytes(number); //<---- Use this
String hexString = Integer.toHexString(reversedBytes);
 

Dark Void

Mitglied
C# isn´t compatible with Java...:pueh:
Integer.reverseBytes is the way to go:
Java:
int number = Integer.parseInt(input);   
int reversedBytes = Integer.reverseBytes(number); //<---- Use this
String hexString = Integer.toHexString(reversedBytes);
Great solution!:)
We still need a way to format the "hexString" variable to 8 bytes (or any other amount) for any result. Putting 1 would make it 1000000 (7 digits) when using "your" reverseBytes code.
 

Neue Themen


Oben