我需要对 Objective C 中任意精度数字的表示进行位操作。到目前为止,我一直在使用 NSData 对象来保存数字——有没有办法对这些内容进行位移?如果没有,是否有不同的方法来实现这一目标?
问问题
609 次
2 回答
1
使用NSMutableData
您可以获取 a 中的字节char
,移动您的位并将其替换为-replaceBytesInRange:withBytes:
.
除了使用缓冲区编写自己的日期保持器类char *
来保存原始数据之外,我没有看到任何其他解决方案。
于 2012-08-30T22:11:09.603 回答
1
如您所见,Apple 不提供任意精度支持。没有提供比vecLib中的 1024 位整数更大的内容。
我也不认为NSData
提供轮班和轮班。所以你将不得不自己动手。例如一个非常幼稚的版本,当我在这里直接输入时可能会有一些小错误:
@interface NSData (Shifts)
- (NSData *)dataByShiftingLeft:(NSUInteger)bitCount
{
// we'll work byte by byte
int wholeBytes = bitCount >> 3;
int extraBits = bitCount&7;
NSMutableData *newData = [NSMutableData dataWithLength:self.length + wholeBytes + (extraBits ? 1 : 0)];
if(extraBits)
{
uint8_t *sourceBytes = [self bytes];
uint8_t *destinationBytes = [newData mutableBytes];
for(int index = 0; index < self.length-1; index++)
{
destinationBytes[index] =
(sourceBytes[index] >> (8-extraBits)) |
(sourceBytes[index+1] << extraBits);
}
destinationBytes[index] = roll >> (8-extraBits);
}
else
/* just copy all of self into the beginning of newData */
return newData;
}
@end
当然,这假设您想要移动的位数本身可以表示为NSUInteger
,以及其他罪过。
于 2012-08-30T22:22:37.793 回答