What is the formula to convert the value of a textfield from hex to little endian?
Example input: 5A109061
Example output: 1636831322
Get the value from the EditText
as a String
.
Parse the string value as hex, using Integer.parseInt(...)
and radix 16
.
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
Use ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.allocate(8)order(ByteOrder.LITTLE_ENDIAN).putLong(5A109061)
byte[] result = byteBuffer.array();
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
}