将uint8_t转换为NSString

时间:2013-11-15 17:01:55

标签: ios objective-c encoding character-encoding nsstring

刚开始学习objective-c并试图将一个字节数组转换为UTF8 NSString,但是它已经变为nil / null。 这是缩写代码示例。

enum {
  TMessageType_CALL = 1,
  TMessageType_REPLY = 2,
  TMessageType_EXCEPTION = 3,
  TMessageType_ONEWAY = 4
};

int32_t VERSION_1 = 0x80010000;

int value = VERSION_1 | TMessageType_CALL;
uint8_t buff[4];
buff[0] = 0xFF & (value >> 24);
buff[1] = 0xFF & (value >> 16);
buff[2] = 0xFF & (value >> 8);
buff[3] = 0xFF & value;

  //Convert buff to NSString with offset =0, length =4

我尝试了以下内容。

NSString *t = [[NSString alloc] initWithBytes:buff length:4 encoding:NSUTF8StringEncoding];
NSString *t1 = [NSString stringWithUTF8String:(char *)buff];

tt1都返回nil 什么是正确转换它的API? 这种转换需要在WriteI32()writeI64(),writeString(),writeDouble()之间是通用的。以下是其余部分的代码。

- (void) writeI16: (short) value
{
  uint8_t buff[2];
  buff[0] = 0xff & (value >> 8);
  buff[1] = 0xff & value;
  [mTransport write: buff offset: 0 length: 2];
}


- (void) writeI64: (int64_t) value
{
  uint8_t buff[8];
  buff[0] = 0xFF & (value >> 56);
  buff[1] = 0xFF & (value >> 48);
  buff[2] = 0xFF & (value >> 40);
  buff[3] = 0xFF & (value >> 32);
  buff[4] = 0xFF & (value >> 24);
  buff[5] = 0xFF & (value >> 16);
  buff[6] = 0xFF & (value >> 8);
  buff[7] = 0xFF & value;
  [mTransport write: buff offset: 0 length: 8];
}

- (void) writeDouble: (double) value
{
  // spit out IEEE 754 bits - FIXME - will this get us in trouble on
  // PowerPC?
  [self writeI64: *((int64_t *) &value)];
}


- (void) writeString: (NSString *) value
{
  if (value != nil) {
    const char * utf8Bytes = [value UTF8String];
    size_t length = strlen(utf8Bytes);
    [self writeI32: length];
    [mTransport write: (uint8_t *) utf8Bytes offset: 0 length: length];
  } else {
    // instead of crashing when we get null, let's write out a zero
    // length string
    [self writeI32: 0];
  }
}

1 个答案:

答案 0 :(得分:4)

buff是一个unsigned char的数组,所以你可以使用它:

NSString *t = [NSString stringWithFormat:@"%s", buff];

作为替代方案,您可以明确地获取每个角色:

NSMutableString *t = [NSMutableString stringWithCapacity:4];
for (NSUInteger i = 0; i < 4; ++i)
    [t appendFormat:@"%c", buff[i]];
NSLog(@"%@", t);

第一个选项转换为有效字符串。第二个选项为您提供每个字符,无论任何终止字符('\ 0')。

我不确定这会给你什么有用的信息,但是你有它。