Sorry if this seems really simple, I just can't find it anywhere online.
I have a UInt8 in hex, I need to get it to a decimal. How do I achieve this in swift?
For example:
"ff"
Thanks
If you have a string representation, "ff", you can use UInt8(_:radix:):
let string = "ff"
if let value = UInt8(string, radix: 16) {
print(value)
}
Try this code, It's work for me.
// Hex to decimal
let h2 = "ff"
let d4 = Int(h2, radix: 16)!
print(d4)
Hope this is help for some one
you can use the function strtoul to convert your hex to decimal:
let result = UInt8(strtoul("ff", nil, 16)) // 255
If your HEX value is not a String, but just something you want to convert compile-time, you can also use:
let integer : UInt8 = 0xff
So prefixing it with 0x will do the job.
Related
What would be the fastest way to convert a String number "1234.5678" to an NSNumber with precision -> 1234.56 and back to String "1234.56".
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.string(from: numberFormatter.number(from: "1234.534234")!)
This code does not look that beautiful. Any ideas?
You can use the new formatted method and specify the number of precision fraction length to two:
let decimal = Decimal(
sign: .plus,
exponent: -4,
significand: 12345678
) // 1234.5678
decimal.formatted(.number.precision(.fractionLength(2))) // "1,234.57"
decimal.formatted(.number.grouping(.never).precision(.fractionLength(2))) // "1234.57"
decimal.formatted(.number.grouping(.never).rounded(rule: .towardZero).precision(.fractionLength(2))) // "1234.56"
Alternatively if you are only interested in the string regardless of any numeric modification like rounding you can strip the unwanted characters with Regular Expression
let string = "1234.5678"
let trimmedString = string.replacingOccurrences(of: "(\\d+\\.\\d{2})\\d.",
with: "$1",
options: .regularExpression)
Many versions of this question are posted. My question is slightly different, as I'm getting conflicting results.
If I run the following in a playground, it works fine:
let myNumber = 12345
if let myHex = Double(String(myNumber, radix: 16)) {
print(myHex)
} else {
print("Bad input as hexadecimal: \(myNumber)")
}
This returns 3039.
However, if I change myNumber to 1234, I get the Bad Input message. Can anyone see what I'm doing wrong, or point me to a similar question? (I have looked)
You are taking a number, 1234, and converting it to a string (e.g. 4d2). You're then asking Double to try to interpret that alphanumeric hex string, which it obviously cannot do.
If you want the hex string representation, it is simply:
let myNumber = 1234
let myHex = String(myNumber, radix: 16)
print(myHex)
Your value of 12345 resulted in a hex string that did not happen to contain any a-f characters (it was 3039), so the Double conversion did not fail. (But it also didn't return the right value, either.)
I am starting to experiment in Swift Playgrounds to familiarize myself with the language. To repeat my question: In Swift 5, how do I display the raw bits returned from range.UpperBound or range.LowerBound in a readable way (with ints)?
As an example, let's say I have a string var myStr = "Hello World!" and I was looking to see if a 'substring' exists in myStr in order. If it does, then I would like to print the indices of that found range:
var myStr = "Hello World!"
if let rangeFound = myStr.range(of: "ello"){
print(rangeFound) //Im getting: Index(_rawBits: 65536)..<Index(_rawBits: 327680)
print("Found ello from \(rangeFound.lowerBound) to \(rangeFound.upperBound)")
//prints: Found ello from Index(_rawBits: 65536) to Index(_rawBits: 327680)
}
Instead of printing the raw bits I would like to print the readable indices ..."from 1 to 4"
I am not trying to use these numbers in another range, only trying to print the readable indices. Thanks
An Unicode character can consist of more than one byte so an index cannot be simply Int.
A workaround to get the integer indices is a conversion to NSRange
let myStr = "Hello World!"
if let rangeFound = myStr.range(of: "ello"){
let nsRange = NSRange(rangeFound, in: myStr)
print("Found ello from \(nsRange.location) to \(nsRange.location + nsRange.length - 1)")
}
I'm currently trying to use the function
Int(binaryString, radix: 2)
to convert a string of binary to an Int. However, this function seems to always be converting the binary string into an unsigned integer. For example,
Int("1111111110011100", radix: 2)
returns 65436 when I'd expect to get -100 from it if it were doing an signed int conversion. I haven't really worked with binary much, so I was wondering what I should do here? Is there a code-efficient way built-into Swift3 that does this for signed ints? I had initially expected this to work because it's an Int constructor (not UInt).
Playing around you can get the desired result as follows:
let binaryString = "1111111110011100"
print(Int(binaryString, radix: 2)!)
print(UInt16(binaryString, radix: 2)!)
print(Int16(bitPattern: UInt16(binaryString, radix: 2)!))
Output:
65436
65436
-100
The desired result comes from creating a signed Int16 using the bit pattern of a UInt16.
Im reading accelerometer data from an ibeacon that appears in the following string format:
x hex string value: "0160"
y hex string value: "ff14"
z hex string value: "0114"
Im expecting to see these values as double values ranging from 0g to 1g. How would you convert these hex strings into doubles in swift?
Get the integer value from hex string with Int(_:radix:)
let string = "ff14"
let hexValue = Int(string, radix: 16)!
and divide by 65535 (16 bit) to get values between 0.0 and 1.0
let result = Double(hexValue) / 65535