4

What is the formula to convert the value of a textfield from hex to little endian?

Example input: 5A109061

Example output: 1636831322

Drenmi
  • 8,492
  • 4
  • 42
  • 51
Jack
  • 69
  • 1
  • 2
  • 8

3 Answers3

4
  1. Get the value from the EditText as a String.

  2. Parse the string value as hex, using Integer.parseInt(...) and radix 16.

  3. Flip the byte order of the int, either using ByteBuffer (simpler) or using bit shifts (faster).

For example:

String hex = "5A109061"; // mEditText.getText().toString()

// Parse hex to int
int value = Integer.parseInt(hex, 16);

// Flip byte order using ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.asIntBuffer().put(value);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int flipped = buffer.asIntBuffer().get();

System.out.println("hex: 0x" + hex);
System.out.println("flipped: " + flipped);

Output:

hex: 0x5A109061
flipped: 1636831322
Harald K
  • 26,314
  • 7
  • 65
  • 111
0

Use ByteBuffer

ByteBuffer byteBuffer = ByteBuffer.allocate(8)order(ByteOrder.LITTLE_ENDIAN).putLong(5A109061)

byte[] result = byteBuffer.array();
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

You can also use this extension for kotlin.

Example :

val str = "6a3b7043"
val hex2Float = str.hex2Float
fun String.hex2Float(): Float{
 val i = toLong(16)
 val data = java.lang.Float.intBitsToFloat(i.toInt()) // Big endian
 val buffer = ByteBuffer.allocate(4)
 buffer.asFloatBuffer().put(data)
 buffer.order(ByteOrder.LITTLE_ENDIAN) 
 val lData = buffer.asFloatBuffer().get() // Little endian
 return lData
}
    
Bhavin Chauhan
  • 1,950
  • 1
  • 26
  • 47