How do I convert my data to small format?

var val = 1240;

      

converts to small endian formate swift 3

Example: 1500 (0x5DC)

before0xDC050000

+3


source to share


4 answers


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

      



-1


source


let value = UInt16(bigEndian: 1500)

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

      

Make sure you are using an initializer bigEndian

.



With 32-bit integers:

let value = UInt32(bigEndian: 1500)

print(String(format:"%08X", value.bigEndian)) //000005DC
print(String(format:"%08X", value.littleEndian)) //DC050000

      

+2


source


If you want 1500 as a byte array in order of order:

var value = UInt32(littleEndian: 1500)

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

      

If you want it like Data

:

let data = Data(array)

      

Or, if you really wanted it to be a hex string:

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

      

+1


source


You can do something like

//: Playground - noun: a place where people can play

import UIKit

extension String {
    func hexadecimal() -> Data? {
        var data = Data(capacity: count / 2)
        let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
        regex.enumerateMatches(in: self, range: NSRange(location: 0, length: utf16.count)) { match, _, _ in
            let byteString = (self as NSString).substring(with: match!.range)
            var num = UInt8(byteString, radix: 16)!
            data.append(&num, count: 1)
        }
        guard !data.isEmpty else { return nil }
        return data
    }
}


func convertInputValue<T: FixedWidthInteger>(_ inputValue: Data) -> T where T: CVarArg {
    let stride = MemoryLayout<T>.stride
    assert(inputValue.count % (stride / 2) == 0, "invalid pack size")

    let fwInt = T.init(littleEndian: inputValue.withUnsafeBytes { $0.pointee })
    let valuefwInt = String(format: "%0\(stride)x", fwInt).capitalized
    print(valuefwInt)
    return fwInt
}

var inputString = "479F"
var inputValue: Data! = inputString.hexadecimal()
let val: UInt16 = convertInputValue(inputValue) //9F47

inputString = "479F8253"
inputValue = inputString.hexadecimal()
let val2: UInt32 = convertInputValue(inputValue) //53829F47

      

0


source







All Articles