Convert Hexa to Decimal in Swift
I want to convert Hexa value into decimal. So I have tried this. When value is >0, then it is working fine. But when value is <0, then is returns wrong value.
let h2 = “0373” let d4 = Int(h2, radix: 16)! print(d4) // 883 let h3 = “FF88” let d5 = Int(h3, radix: 16)! print(d5) // 65416
When I am passing FF88, then it returns 65416. But actually it is -120.
Right now, I am following this Convert between Decimal, Binary and Hexadecimal in Swift answer. But it didn’t works always.
Please check this conversation online. Please see following image for more details of this conversation.
Is there any other solution for get minus decimal from Hexa value.?
Any help would be appreciated !!
- How to convert Decimal to String with two digits after separator?
- ios - dynamically create and display unicode strings
- Limit a double to two decimal places without trailing zeros
- NSNumberFormatter with comma decimal separator
- Objective-C - Get number of decimals of a double variable
- How to convert hexadecimal string to decimal?
2 Solutions Collect From Internet About “Convert Hexa to Decimal in Swift”
FF 88 is the hexadecimal representation of the 16-bit signed integer
-120. You can create an unsigned integer first and then convert it
to the signed counterpart with the same bit pattern:
let h3 = "FF88" let u3 = UInt16(h3, radix: 16)! // 65416 let s3 = Int16(bitPattern: u3) // -120
Hexadecimal conversion depends on integer Type (
signed , unsigned ) and size (
64 bits , 32 bits , 16 bits . . ) , this is what you missed .
source code :
let h3 = "FF88" let d5 = Int16(truncatingBitPattern: strtoul(h3, nil, 16)) print(d5) // -120
- iPhone Wifi Scan Stumbler
- How to override @synthesized getters?
- can I split a numeric string using multiple separators in a Swift closure?
- Xcode 4: Build Failed, No Issues
- Should I create a unique Apple App ID per application for the App Store?
- Xcode STL C++ Debug compile error
- UITableView reloadData automatically calls resignFirstResponder
- NSExpression custom variables inside expression
- Xcode Playground Timeline empty
- How do I import a swift function declared in a compiled .swiftmodule into another swift file?
- How to build against older iOS versions with the latest Xcode downloads?
- How to deprecate a method in Xcode
- MapKit in Swift, Part 2
- How to display a PDF document that includes hyperlinks? (on iOS)
- How to install Cocos2d PROJECT templates in Xcode 4?