【问题标题】:Arbitrary precision bit manipulation (Objective C)任意精度位操作(目标 C)
【发布时间】:2012-08-30 21:23:57
【问题描述】:

我需要在 Objective C 中对任意精度数字的表示进行位操作。到目前为止,我一直在使用 NSData 对象来保存数字 - 有没有办法对这些内容的内容进行位移?如果没有,是否有其他方法可以实现这一目标?

【问题讨论】:

    标签: objective-c integer bit-manipulation nsdata arbitrary-precision


    【解决方案1】:

    使用NSMutableData,您可以获取char 中的字节,移动您的位并将其替换为-replaceBytesInRange:withBytes:

    除了使用char * 缓冲区编写您自己的日期保持器类来保存原始数据之外,我没有看到任何其他解决方案。

    【讨论】:

      【解决方案2】:

      如您所见,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,以及其他错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 1970-01-01
        相关资源
        最近更新 更多