How to Convert a Hex to Signed Float in Swift? Works Fine with Positive Number But Doesn't Work on Negative

pow returns different results using Double or Decimal with negative exponent

I think that this struct give us an idea about the problem:

public struct Decimal {

public var _exponent: Int32

public var _length: UInt32 // length == 0 && isNegative -> NaN

public var _isNegative: UInt32

public var _isCompact: UInt32

public var _reserved: UInt32

public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)

public init()

public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16))
}

The length condition should be satisfacted only length == 0, but as UInt32 doesn't represents fractionary numbers the condition is satisfacted...

Is floating point math broken?

Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.

For 0.1 in the standard binary64 format, the representation can be written exactly as

  • 0.1000000000000000055511151231257827021181583404541015625 in decimal, or
  • 0x1.999999999999ap-4 in C99 hexfloat notation.

In contrast, the rational number 0.1, which is 1/10, can be written exactly as

  • 0.1 in decimal, or
  • 0x1.99999999999999...p-4 in an analogue of C99 hexfloat notation, where the ... represents an unending sequence of 9's.

The constants 0.2 and 0.3 in your program will also be approximations to their true values. It happens that the closest double to 0.2 is larger than the rational number 0.2 but that the closest double to 0.3 is smaller than the rational number 0.3. The sum of 0.1 and 0.2 winds up being larger than the rational number 0.3 and hence disagreeing with the constant in your code.

A fairly comprehensive treatment of floating-point arithmetic issues is What Every Computer Scientist Should Know About Floating-Point Arithmetic. For an easier-to-digest explanation, see floating-point-gui.de.

Side Note: All positional (base-N) number systems share this problem with precision

Plain old decimal (base 10) numbers have the same issues, which is why numbers like 1/3 end up as 0.333333333...

You've just stumbled on a number (3/10) that happens to be easy to represent with the decimal system, but doesn't fit the binary system. It goes both ways (to some small degree) as well: 1/16 is an ugly number in decimal (0.0625), but in binary it looks as neat as a 10,000th does in decimal (0.0001)** - if we were in the habit of using a base-2 number system in our daily lives, you'd even look at that number and instinctively understand you could arrive there by halving something, halving it again, and again and again.

Of course, that's not exactly how floating-point numbers are stored in memory (they use a form of scientific notation). However, it does illustrate the point that binary floating-point precision errors tend to crop up because the "real world" numbers we are usually interested in working with are so often powers of ten - but only because we use a decimal number system day-to-day. This is also why we'll say things like 71% instead of "5 out of every 7" (71% is an approximation, since 5/7 can't be represented exactly with any decimal number).

So no: binary floating point numbers are not broken, they just happen to be as imperfect as every other base-N number system :)

Side Side Note: Working with Floats in Programming

In practice, this problem of precision means you need to use rounding functions to round your floating point numbers off to however many decimal places you're interested in before you display them.

You also need to replace equality tests with comparisons that allow some amount of tolerance, which means:

Do not do if (x == y) { ... }

Instead do if (abs(x - y) < myToleranceValue) { ... }.

where abs is the absolute value. myToleranceValue needs to be chosen for your particular application - and it will have a lot to do with how much "wiggle room" you are prepared to allow, and what the largest number you are going to be comparing may be (due to loss of precision issues). Beware of "epsilon" style constants in your language of choice. These are not to be used as tolerance values.

Regular expression for floating point numbers

TL;DR

Use [.] instead of \. and [0-9] instead of \d to avoid escaping issues in some languages (like Java).

Thanks to the nameless one for originally recognizing this.

One relatively simple pattern for matching a floating point number in a larger string is:

[+-]?([0-9]*[.])?[0-9]+

This will match:

  • 123
  • 123.456
  • .456

See a working example

If you also want to match 123. (a period with no decimal part), then you'll need a slightly longer expression:

[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)

See pkeller's answer for a fuller explanation of this pattern

If you want to include a wider spectrum of numbers, including scientific notation and non-decimal numbers such as hex and octal, see my answer to How do I identify if a string is a number?.

If you want to validate that an input is a number (rather than finding a number within the input), then you should surround the pattern with ^ and $, like so:

^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$

Irregular Regular Expressions

"Regular expressions", as implemented in most modern languages, APIs, frameworks, libraries, etc., are based on a concept developed in formal language theory. However, software engineers have added many extensions that take these implementations far beyond the formal definition. So, while most regular expression engines resemble one another, there is actually no standard. For this reason, a lot depends on what language, API, framework or library you are using.

(Incidentally, to help reduce confusion, many have taken to using "regex" or "regexp" to describe these enhanced matching languages. See Is a Regex the Same as a Regular Expression? at RexEgg.com for more information.)

That said, most regex engines (actually, all of them, as far as I know) would accept \.. Most likely, there's an issue with escaping.

The Trouble with Escaping

Some languages have built-in support for regexes, such as JavaScript. For those languages that don't, escaping can be a problem.

This is because you are basically coding in a language within a language. Java, for example, uses \ as an escape character within it's strings, so if you want to place a literal backslash character within a string, you must escape it:

// creates a single character string: "\"
String x = "\\";

However, regexes also use the \ character for escaping, so if you want to match a literal \ character, you must escape it for the regex engine, and then escape it again for Java:

// Creates a two-character string: "\\"
// When used as a regex pattern, will match a single character: "\"
String regexPattern = "\\\\";

In your case, you have probably not escaped the backslash character in the language you are programming in:

// will most likely result in an "Illegal escape character" error
String wrongPattern = "\.";
// will result in the string "\."
String correctPattern = "\\.";

All this escaping can get very confusing. If the language you are working with supports raw strings, then you should use those to cut down on the number of backslashes, but not all languages do (most notably: Java). Fortunately, there's an alternative that will work some of the time:

String correctPattern = "[.]";

For a regex engine, \. and [.] mean exactly the same thing. Note that this doesn't work in every case, like newline (\\n), open square bracket (\\[) and backslash (\\\\ or [\\]).

A Note about Matching Numbers

(Hint: It's harder than you think)

Matching a number is one of those things you'd think is quite easy with regex, but it's actually pretty tricky. Let's take a look at your approach, piece by piece:

[-+]?

Match an optional - or +

[0-9]*

Match 0 or more sequential digits

\.?

Match an optional .

[0-9]*

Match 0 or more sequential digits

First, we can clean up this expression a bit by using a character class shorthand for the digits (note that this is also susceptible to the escaping issue mentioned above):

[0-9] = \d

I'm going to use \d below, but keep in mind that it means the same thing as [0-9]. (Well, actually, in some engines \d will match digits from all scripts, so it'll match more than [0-9] will, but that's probably not significant in your case.)

Now, if you look at this carefully, you'll realize that every single part of your pattern is optional. This pattern can match a 0-length string; a string composed only of + or -; or, a string composed only of a .. This is probably not what you've intended.

To fix this, it's helpful to start by "anchoring" your regex with the bare-minimum required string, probably a single digit:

\d+

Now we want to add the decimal part, but it doesn't go where you think it might:

\d+\.?\d* /* This isn't quite correct. */

This will still match values like 123.. Worse, it's got a tinge of evil about it. The period is optional, meaning that you've got two repeated classes side-by-side (\d+ and \d*). This can actually be dangerous if used in just the wrong way, opening your system up to DoS attacks.

To fix this, rather than treating the period as optional, we need to treat it as required (to separate the repeated character classes) and instead make the entire decimal portion optional:

\d+(\.\d+)? /* Better. But... */

This is looking better now. We require a period between the first sequence of digits and the second, but there's a fatal flaw: we can't match .123 because a leading digit is now required.

This is actually pretty easy to fix. Instead of making the "decimal" portion of the number optional, we need to look at it as a sequence of characters: 1 or more numbers that may be prefixed by a . that may be prefixed by 0 or more numbers:

(\d*\.)?\d+

Now we just add the sign:

[+-]?(\d*\.)?\d+

Of course, those slashes are pretty annoying in Java, so we can substitute in our long-form character classes:

[+-]?([0-9]*[.])?[0-9]+

Matching versus Validating

This has come up in the comments a couple times, so I'm adding an addendum on matching versus validating.

The goal of matching is to find some content within the input (the "needle in a haystack"). The goal of validating is to ensure that the input is in an expected format.

Regexes, by their nature, only match text. Given some input, they will either find some matching text or they will not. However, by "snapping" an expression to the beginning and ending of the input with anchor tags (^ and $), we can ensure that no match is found unless the entire input matches the expression, effectively using regexes to validate.

The regex described above ([+-]?([0-9]*[.])?[0-9]+) will match one or more numbers within a target string. So given the input:

apple 1.34 pear 7.98 version 1.2.3.4

The regex will match 1.34, 7.98, 1.2, .3 and .4.

To validate that a given input is a number and nothing but a number, "snap" the expression to the start and end of the input by wrapping it in anchor tags:

^[+-]?([0-9]*[.])?[0-9]+$

This will only find a match if the entire input is a floating point number, and will not find a match if the input contains additional characters. So, given the input 1.2, a match will be found, but given apple 1.2 pear no matches will be found.

Note that some regex engines have a validate, isMatch or similar function, which essentially does what I've described automatically, returning true if a match is found and false if no match is found. Also keep in mind that some engines allow you to set flags which change the definition of ^ and $, matching the beginning/end of a line rather than the beginning/end of the entire input. This is typically not the default, but be on the lookout for these flags.

Allow only Numbers for UITextField input

This is how you might handle the problem on a SSN verification field, you can modify the max length and remove the if statement checking for keyboard type if you need to.

There is also logic to suppress the max length alerts when the user is typing as opposed to pasting data.

Within the context of this code, presentAlert()/presentAlert: is just some basic function that presents a UIAlertController (or a legacy UIAlertView) using the message string passed.

Swift 5

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.
//
// There are also some better stylistic approaches in Swift to avoid all the
// nested statements, but I wanted to keep the styles similar to allow others
// to contrast and compare between the two languages a little easier.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

// Handle backspace/delete
guard !string.isEmpty else {

// Backspace detected, allow text change, no need to process the text any further
return true
}

// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if textField.keyboardType == .numberPad {

// Check for invalid input characters
if CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) {

// Present alert so the user knows what went wrong
presentAlert("This field accepts only numeric entries.")

// Invalid characters detected, disallow text change
return false
}
}

// Length Processing
// Need to convert the NSRange to a Swift-appropriate type
if let text = textField.text, let range = Range(range, in: text) {

let proposedText = text.replacingCharacters(in: range, with: string)

// Check proposed text length does not exceed max character count
guard proposedText.count <= maxCharacters else {

// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if string.count > 1 {

// Pasting text, present alert so the user knows what went wrong
presentAlert("Paste failed: Maximum character count exceeded.")
}

// Character count exceeded, disallow text change
return false
}

// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
answerButton.isEnabled = (proposedText.count == 4)
}

// Allow text change
return true
}

Objective-C

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Handle backspace/delete
if (!string.length)
{
// Backspace detected, allow text change, no need to process the text any further
return YES;
}

// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if (textField.keyboardType == UIKeyboardTypeNumberPad)
{
if ([string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location != NSNotFound)
{
[self presentAlert: @"This field accepts only numeric entries."];
return NO;
}
}

// Length Validation
NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];

// Check proposed text length does not exceed max character count
if (proposedText.length > maxCharacters)
{
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if (string.length > 1)
{
// Pasting text, present alert so the user knows what went wrong
[self presentAlert: @"Paste failed: Maximum character count exceeded."];
}

// Character count exceeded, disallow text change
return NO;
}

// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
self.answerButton.enabled = (proposedText.length == maxCharacters);

// Allow text change
return YES;
}

Peripheral and Central at the same time on the same app iOS11

I'm getting back with the correct way of achieving the required functionality. After initialising the peripheralManager, create a CBMutableService and hold a reference to it(declared at the top of the class).

var globalService:CBMutableService? = nil

Next step is to check for the peripheralManager state, and do all the required work after you receive the poweredOn state:

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch(peripheral.state)

case.poweredOn:
print("Peripheral service is powered on")

createServiceWithCharacteristics()
}

func createServiceWithCharacteristics(){

let serviceUUID:CBUUID = CBUUID(string: self.service_uuid_string)
let featureCharacteristicUUID:CBUUID = CBUUID(string: self.feature_characteristic_uuid_string)

// Start with the CBMutableCharacteristic
let permissions: CBAttributePermissions = [.readable, .writeable]
let properties: CBCharacteristicProperties = [.notify, .read, .write]

self.featureCharacteristic = CBMutableCharacteristic(type: featureCharacteristicUUID, properties: properties , value: nil, permissions: permissions)

// Then the service
let localService = CBMutableService(type: serviceUUID, primary: true)

// Add the characteristic to the service
localService.characteristics = [featureCharacteristic!]
globalService = localService

// And add it to the peripheral manager
self.peripheralManager?.add(globalService!)
print("Start advertising.")
peripheralManager?.startAdvertising([CBAdvertisementDataLocalNameKey:"Name"])
}

Catch and compute overflow during multiplication of two large integers

1. Detecting the overflow:

x = a * b;
if (a != 0 && x / a != b) {
// overflow handling
}

Edit: Fixed division by 0 (thanks Mark!)

2. Computing the carry is quite involved. One approach is to split both operands into half-words, then apply long multiplication to the half-words:

uint64_t hi(uint64_t x) {
return x >> 32;
}

uint64_t lo(uint64_t x) {
return ((1ULL << 32) - 1) & x;
}

void multiply(uint64_t a, uint64_t b) {
// actually uint32_t would do, but the casting is annoying
uint64_t s0, s1, s2, s3;

uint64_t x = lo(a) * lo(b);
s0 = lo(x);

x = hi(a) * lo(b) + hi(x);
s1 = lo(x);
s2 = hi(x);

x = s1 + lo(a) * hi(b);
s1 = lo(x);

x = s2 + hi(a) * hi(b) + hi(x);
s2 = lo(x);
s3 = hi(x);

uint64_t result = s1 << 32 | s0;
uint64_t carry = s3 << 32 | s2;
}

To see that none of the partial sums themselves can overflow, we consider the worst case:

        x = s2 + hi(a) * hi(b) + hi(x)

Let B = 1 << 32. We then have

            x <= (B - 1) + (B - 1)(B - 1) + (B - 1)
<= B*B - 1
< B*B

I believe this will work - at least it handles Sjlver's test case. Aside from that, it is untested (and might not even compile, as I don't have a C++ compiler at hand anymore).

How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

I was also facing this problem. I also have feelings that in iOS 7 there is more space. And I figured out that this is about 10 points more. I usually use negative spaces when I want for LeftBarItemButton to start from the edge. This can be useful for you as well.

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

negativeSpacer.width = -16; // it was -6 in iOS 6

[self.navigationItem setLeftBarButtonItems:@[negativeSpacer, requiredButton]; /* this will be the button which you actually need */] animated:NO];


Related Topics



Leave a reply



Submit