将二进制字符串转换为NSInteger

时间:2011-05-18 08:43:59

标签: objective-c

有人在Objective-C中有一些代码将二进制字符串转换为NSInteger吗?

示例:

111000 -> 56

1 个答案:

答案 0 :(得分: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
}