说我有一个NSString NSString * myIpAddress = @“192.168.1.1”
我想将其转换为整数 - 将其递增,然后将其转换回NSString。
除了使用位掩码和移位以及sprintf之外,iOS还有一种简单的方法吗?
答案 0 :(得分:5)
这样的事情就是我在my app中做的事情:
NSArray *ipExplode = [string componentsSeparatedByString:@"."];
int seg1 = [ipExplode[0] intValue];
int seg2 = [ipExplode[1] intValue];
int seg3 = [ipExplode[2] intValue];
int seg4 = [ipExplode[3] intValue];
uint32_t newIP = 0;
newIP |= (uint32_t)((seg1 & 0xFF) << 24);
newIP |= (uint32_t)((seg2 & 0xFF) << 16);
newIP |= (uint32_t)((seg3 & 0xFF) << 8);
newIP |= (uint32_t)((seg4 & 0xFF) << 0);
newIP++;
NSString *newIPStr = [NSString stringWithFormat:@"%u.%u.%u.%u",
((newIP >> 24) & 0xFF),
((newIP >> 16) & 0xFF),
((newIP >> 8) & 0xFF),
((newIP >> 0) & 0xFF)];