NSString to UInt64 - ios

How do you convert from NSString to UInt64?
For example, something like this if a UInt64Value helper method existed:
NSString *value = #"1234567";
UInt64 convertedValue = [value UInt64Value];
I am trying to do this in an iOS project.

To pitch another possibility for completeness:
NSScanner *scanner = [NSScanner scannerWithString:value];
unsigned long long convertedValue = 0;
[scanner scanUnsignedLongLong:&convertedValue];
return convertedValue;
... check the result on scanUnsignedLongLong if you want to differentiate between finding a value of 0 and finding something that isn't a number.

NSString * num = #"123456";
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc]init];
NSNumber * number = [numberFormatter numberFromString:num];
unsigned long long valueUInt64 = number.unsignedLongLongValue;

You can use strtoull(const char *, char **, int) as following:
NSString *value = #"1234567";
UInt64 convertedValue = strtoull([value UTF8String], NULL, 0);

You can get a UInt64 with longLongValue
NSString *str = #"23147653105732";
UInt64 uint64 = [str longLongValue];
Another way to get an int64 is:
NSString *str = #"23147653105732";
int64_t int64_t = atoll([str UTF8String]);

Related

Convert NSString that represents HEX value to hex (#"0d" to 0x0d) [duplicate]

This question already has answers here:
NSString (hex) to bytes
(7 answers)
Closed 5 years ago.
I want to convert ObjectiveC NSString, that contains for example string "0d" to hex value 0x0d. What's the easiest way to achieve that?
Example:
NSString *str = #"50";
unsigned char mac[1];
mac[0] = 0x50; //<- how to set mac[0] to 0x50 from "str" string?
- (NSData *)dataFromHexString {
const char *chars = [self UTF8String];
int i = 0, len = self.length;
NSMutableData *data = [NSMutableData dataWithCapacity:len/2];
char byteChars[3] = {chars[0],chars[1],'\0'};
unsigned long wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
return data;
}

Best way to get length of UTF-8 string in bytes?

I want to get a cString from NSString.
So we used c​String​Using​Encoding:​ method.
However, the return value of the c​String​Using​Encoding:​ method is not guaranteed.
(Apple's doc: The returned C string is guaranteed to be valid only until either the receiver is freed.)
So Apple recommends the get​CString:​max​Length:​encoding: method.
I want to pass the exact length to maxLength.
Example 1)
NSString *tmp = #"中日韓" // cString 9bytes
char *buffer = new tmp[9 + 1];
[tmp getCString:buffer maxLength:9+1 encoding:NSUTF8String​Encoding];
Example 2)
NSString *tmp = #"中日韓123" // cString 12bytes
char *buffer = new tmp[12 + 1];
[tmp getCString:buffer maxLength:12+1 encoding:NSUTF8String​Encoding];
Is there a way to know the lengths of 9 and 12 in the example above?
// Add one because this doesn't include the NULL
NSUInteger maxLength = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
You can use cStringUsingEncoding to get the length. If you need the resulting char * to live longer than tmp, then simply copy the C-string:
NSString *tmp = #"中日韓" // cString 9bytes
const char *cStr = [tmp cStringUsingEncoding:NSUTF8StringEncoding];
size_t len = strlen(cStr);
char *buffer = new tmp[len + 1];
strcpy(buffer, cStr);

How to get NSData From Hex String?

I need to send data over melodyManager & free from NonHexCharacters,
I already gone throught link How to convert an NSData into an NSString Hex string?
NSData from hex String?
In Both links i am not able to get NonHexFree charater data.
My input string is this,
0x0009 0xB0 0xFD 0xC2 0xA1 0x06 0x01%#040404 0x01 0xss1 0xhh 0xyy1
I need to convert this string into NSData which is free from nonhex characters i mean data should get only of hex string like from 0-9 symbols & A, B, C, D, E, F (alternatively a, b, c, d, e, f) and also remove space with 0x prefixes & output string should be 0009B0FDC2A10601040404111
then it should get converted to `NSData'
For cleaning nonHex characters check this,
NSString *input = #"0x0009 0xB0 0xFD 0xC2 0xA1 0x06 0x01%#040404 0x01 0xss1 0xhh 0xyy1";
I am considering that you don't required '0x' into your case.
NSString * output = [input stringByReplacingOccurrencesOfString:#"0x" withString:#""
options:NSCaseInsensitiveSearch range:NSMakeRange(0, input.length)];
NSString * hexChars = #"0123456789abcdefABCDEF";
NSCharacterSet *hexc = [NSCharacterSet characterSetWithCharactersInString:hexChars];
NSCharacterSet *invalidHexc = [hexc invertedSet];
NSString * allHex = [[output componentsSeparatedByCharactersInSet:invalidHexc] componentsJoinedByString:#""];
Then resultant hexstring pass to scan hexString & append into NSMUtableData then convert it into NSData,
//Check condition if required `allHex.lenght != nil`
NSMutableData *result = [[NSMutableData alloc] init];
int i = 0;
for (i = 0; i+2 <= allHex.length; i+=2) {
NSRange range = NSMakeRange(i, 2);
NSString* hexStr = [allHex substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
unsigned char uc = (unsigned char) intValue;
[result appendBytes:&uc length:1];
}
NSData * data = [NSData dataWithData:result];

I am converting NSString a=#"0x401A" into int16_t?

Why when I am trying to convert it converts hexadecimal value into integer?
unsigned int outVal;
NSScanner* scanner = [NSScanner scannerWithString:final1];
[scanner scanHexInt:&outVal];
NSLog(#"%u",outVal);
Another way I am trying to do is converting it to normal integer it gives me 0 value.
I just want the same characters:
int16_t a=0x401A;
I am getting this number from user so dont have the control to define it myself. I want removed quotations and datatype int16_t so I can execute command.
I got the solution myself
first the function which converts the data into bytes
- (NSData *)dataWithString:(NSString *)hexstring
{
NSMutableData* data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= hexstring.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [hexstring substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
and call the function by giving parameters in the command which will be sent to BLE
NSData * data = [self dataWithString: #"401A"];
[peripheral writeValue:data forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
Through this code anybody can sent string to BLE device. Thanks and Cheers

Trouble converting NSData to int

I have an NSData object that contains just <64> which is supposed to represent the int 100
How can I convert this NSData to an int?
I can convert it to it's Chr equivalent d using
NSString *string = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
but I need the Dec equivalent of 100
Thanks
<64> means that the NSData object contains a single byte with the value 0x64 = 100,
so the following should work;
const uint8_t *bytes = [data bytes]; // pointer to the bytes in data
int value = bytes[0]; // first byte
int *b = (int *)data.bytes;
printf("%d",*b); //prints 100
Below logic converts NSData to integer perefctly. Length of bytes does not matter. It just works.
NSData *data;
NSString *stringData = [data description];
stringData = [stringData substringWithRange:NSMakeRange(1, [stringData length]-2)];
unsigned dataAsInt = 0;
NSScanner *scanner = [NSScanner scannerWithString: stringData];
[scanner scanHexInt:& dataAsInt];

Resources