Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Little endian hex value to decimal

I'm having difficulties implementing a function converting hex value(little endian) to decimal value.

So I'm writing function:

func convertHexLittleEndianToDeciaml(input:String) -> (int) 

and Input is always 4 bytes(so 8 characters in input string)

value for convertHexLittleEndianToDeciaml("606d0000") should return 28,000

like image 878
androisojavaswift Avatar asked Dec 05 '25 07:12

androisojavaswift


1 Answers

You can write something like this: (See UPDATEs)

func convertHexLittleEndianToDeciaml(input:String) -> Int32 {
    if let beValue = Int32(input, radix: 16) where input.characters.count == 8 {
        return beValue.byteSwapped
    } else {
        //or `fatalError()` or `return 0` or ...
        return Int32.min
    }
}

print(convertHexLittleEndianToDeciaml("606d0000")) //->28000

UPDATE

Sorry, but the code above have some overflow issue, happens with something like "FF010000":

func convertHexLittleEndianToDeciaml(input:String) -> Int32 {
    if let beValue = UInt32(input, radix: 16) where input.characters.count == 8 {
        return Int32(bitPattern: beValue.byteSwapped)
    } else {
        //or `fatalError()` or `return 0` or ...
        return Int32.min
    }
}

UPDATE2

So, I have found that returning a valid Int32 in error case might cause a bug which cannot easily be found. I recommend you to change the return type to Optional and return nil in error case.

func convertHexLittleEndianToDeciaml(input:String) -> Int32? {
    guard let beValue = UInt32(input, radix: 16) where input.characters.count == 8 else {
        return nil
    }
    return Int32(bitPattern: beValue.byteSwapped)
}

if let value = convertHexLittleEndianToDeciaml("606d0000") {
    print(value) //->28000
} else {
    print("Hex format invalid")
}
like image 67
OOPer Avatar answered Dec 07 '25 19:12

OOPer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!