按长度检索 NSData 到十六进制

发布于 2024-12-10 06:08:20 字数 109 浏览 6 评论 0原文

我得到了一个 NSData,其中包含类似 <00350029 0033> 的字节长度为 6,是否有任何正确的方法可以将字节分割为数组,例如 (00, 35, 00, 29, 00, 33) ?

I got a NSData that contain bytes like <00350029 0033> with length 6, is there any correct way to split the bytes to array somehow like (00, 35, 00, 29, 00, 33) ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花期渐远 2024-12-17 06:08:20
NSData *data = ...;
NSMutableArray *bytes = [NSMutableArray array];
for (NSUInteger i = 0; i < [data length]; i++) {
    unsigned char byte;
    [data getBytes:&byte range:NSMakeRange(i, 1)];
    [bytes addObject:[NSString stringWithFormat:@"%x", byte]];
}
NSLog(@"%@", bytes);

(假设您希望字节作为十六进制字符串表示形式,如示例中所示。否则,请使用 NSNumber。)

NSData *data = ...;
NSMutableArray *bytes = [NSMutableArray array];
for (NSUInteger i = 0; i < [data length]; i++) {
    unsigned char byte;
    [data getBytes:&byte range:NSMakeRange(i, 1)];
    [bytes addObject:[NSString stringWithFormat:@"%x", byte]];
}
NSLog(@"%@", bytes);

(Assuming you want the bytes as a hex string representation, as in your example. Otherwise, use NSNumber.)

花桑 2024-12-17 06:08:20

您可以使用 NSData 方法

- (void)getBytes:(void *)buffer range:(NSRange)range

获取给定范围内的字节(在使用 malloc 分配正确数量的内存之后),然后用于

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

创建新的小(1 字节长)数据对象,然后将其放入数组中。但是,如果您只是检索指向字节本身的指针(使用 [data bytes]),则会为您提供一个指针(一种 C 意义上的数组,而不是 NSArray,但也可以使用并且效率更高)。

You could use the NSData method

- (void)getBytes:(void *)buffer range:(NSRange)range

to get the bytes in a given range (after having allocated the right amount of memory, using malloc), then use

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

to create new small (1 byte long) data objects which you then put into an array. However if you just retrieve the pointer to the bytes themselves (using [data bytes]), that gives you a pointer (kind of an array in the C sense, not an NSArray, but could also be used and far more efficient).

陌伤ぢ 2024-12-17 06:08:20
static NSString* HexStringFromNSData(NSData* data) {
    NSUInteger n = data.length;
    NSMutableString* s = [NSMutableString stringWithCapacity:(2 * n)];
    const unsigned char* ptr = [data bytes];
    for(NSUInteger i = 0; i < n; i++, ptr++) {
        [s appendFormat:@"%02x", (long)*ptr];
    }
    return [NSString stringWithString:s];
}
static NSString* HexStringFromNSData(NSData* data) {
    NSUInteger n = data.length;
    NSMutableString* s = [NSMutableString stringWithCapacity:(2 * n)];
    const unsigned char* ptr = [data bytes];
    for(NSUInteger i = 0; i < n; i++, ptr++) {
        [s appendFormat:@"%02x", (long)*ptr];
    }
    return [NSString stringWithString:s];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文