Deepak Tagadiya
Deepak Tagadiya

Reputation: 2237

How to convert data into little endian format?

var val = 1240;

convert into little endian formate swift 3

Ex: 1500 (0x5DC) to 0xDC050000

Upvotes: 10

Views: 6685

Answers (4)

hbk
hbk

Reputation: 11184

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

Upvotes: 0

Deepak Tagadiya
Deepak Tagadiya

Reputation: 2237

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

Upvotes: 0

Rob
Rob

Reputation: 437552

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()

Upvotes: 6

Sulthan
Sulthan

Reputation: 130102

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

Upvotes: 6

Related Questions