Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data into little endian format?

Tags:

ios

swift

swift3

var val = 1240;

convert into little endian formate swift 3

Ex: 1500 (0x5DC) to 0xDC050000

like image 569
Deepak Tagadiya Avatar asked Jun 12 '17 09:06

Deepak Tagadiya


People also ask

How do you convert to little endian?

Quickly converting to little-endian. If I want to quickly convert a string of data in to little-endian, I just swap each pair of characters (working from right-to-left), then reverse the string.

How is data stored in little endian?

Little Endian Byte Order: The least significant byte (the "little end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory.

What is little endian format?

Little-endian is an order in which the "little end" (least significant value in the sequence) is stored first.

What is little endian encoding?

Little Endian byte ordering is defined as follows: In a binary number consisting of multiple bytes (e.g., a 32-bit unsigned integer value, the Group Number, the Element Number, etc.), the least significant byte shall be encoded first; with the remaining bytes encoded in increasing order of significance.


2 Answers

let value = UInt16(bigEndian: 1500)

print(String(format:"%04X", value.bigEndian)) //05DC
print(String(format:"%04X", value.littleEndian)) //DC05

Make sure you are actually using the bigEndian initializer.

With 32-bit integers:

let value = UInt32(bigEndian: 1500)

print(String(format:"%08X", value.bigEndian)) //000005DC
print(String(format:"%08X", value.littleEndian)) //DC050000
like image 105
Sulthan Avatar answered Oct 09 '22 21:10

Sulthan


If you want 1500 as an array of bytes in little-endian order:

var value = UInt32(littleEndian: 1500)

let array = withUnsafeBytes(of: &value) { Array($0) }

If you want that as a Data:

let data = Data(array)

Or, if you really wanted that as a hex string:

let string = array.map { String(format: "%02x", $0) }.joined()
like image 25
Rob Avatar answered Oct 09 '22 23:10

Rob