将二进制字符串转换为NSInteger。

时间:2022-10-17 21:24:37

Anybody has some code in Objective-C to convert a binary string to an NSInteger ?

有人用Objective-C代码将二进制字符串转换成NSInteger吗?

example:

例子:

111000 -> 56

1 个解决方案

#1


12  

const char* utf8String = [binaryString UTF8String];
const char* endPtr = NULL;
long int foo = strtol(utf8String, &endPtr, 2);

if (endPtr != utf8String + strlen(utf8String))
{
    // string wasn't entirely a binary number
}
if (errno == ERANGE && (foo == LONG_MAX || foo == LONG_MIN))
{
    // number was too big or too small
}

#1


12  

const char* utf8String = [binaryString UTF8String];
const char* endPtr = NULL;
long int foo = strtol(utf8String, &endPtr, 2);

if (endPtr != utf8String + strlen(utf8String))
{
    // string wasn't entirely a binary number
}
if (errno == ERANGE && (foo == LONG_MAX || foo == LONG_MIN))
{
    // number was too big or too small
}