如何将数据转换为小端格式?

Dee*_*iya 7 ios swift swift3

var val = 1240;
Run Code Online (Sandbox Code Playgroud)

转换为 little endian formate swift 3

例如:1500 (0x5DC)0xDC050000

Sul*_*han 6

let value = UInt16(bigEndian: 1500)

print(String(format:"%04X", value.bigEndian)) //05DC
print(String(format:"%04X", value.littleEndian)) //DC05
Run Code Online (Sandbox Code Playgroud)

确保您实际上正在使用bigEndian初始化程序。

使用 32 位整数:

let value = UInt32(bigEndian: 1500)

print(String(format:"%08X", value.bigEndian)) //000005DC
print(String(format:"%08X", value.littleEndian)) //DC050000
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 5

如果您想要 1500 作为小端顺序的字节数组:

var value = UInt32(littleEndian: 1500)

let array = withUnsafeBytes(of: &value) { Array($0) }
Run Code Online (Sandbox Code Playgroud)

如果您希望将其作为Data

let data = Data(array)
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实希望将其作为十六进制字符串:

let string = array.map { String(format: "%02x", $0) }.joined()
Run Code Online (Sandbox Code Playgroud)


Dee*_*iya 0

                let timeDevide = self.setmiliSecond/100
                var newTime = UInt32(littleEndian: timeDevide)
                let arrayTime = withUnsafeBytes(of: &newTime) 
                 {Array($0)}
                let timeDelayValue = [0x0B] + arrayTime
Run Code Online (Sandbox Code Playgroud)