假设我有一个 NSString NSString *myIpAddress = @"192.168.1.1"
我想将其转换为整数 - 将其递增然后将其转换回 NSString。
除了使用位掩码、移位和 sprintf 之外,iOS 是否有一种简单的方法来做到这一点?
这样的事情是我在我的应用程序中所做的:
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)];