如何将NSData转换为十六进制字符串?

3

我尝试了以下代码将NSData转换为十六进制字符串,但都不正确?

这里的"result"是我的NSData

我需要一个十六进制字符串作为输出,但我没有得到它

NSUInteger dataLength = [result length];
  NSLog(@"%d",dataLength);
    NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
   const unsigned char *dataBytes = [result bytes];
    for (NSInteger idx = 0; idx < dataLength; ++idx) {        [string appendFormat:@"%02x", dataBytes[idx]];
 }    
    NSLog(@"%@",string);

请问我该如何进行转换?

更新:结果数据包含加密字符串。我想将其转换为十六进制值。


1
可能是重复问题.. https://dev59.com/o3M_5IYBdhLWcg3wmkeu - Amar
@mango:有什么问题?你得到了什么输出?你期望得到什么输出? - Martin R
我期望的值是类似于 826ad07e9a2a565e 的。 - user2377290
1
@mango:请展示 输入NSLog(@"%@", result)输出NSLog(@"%@", string) 以及你的 期望结果,否则很难提供帮助!! - Martin R
显示剩余4条评论
5个回答

14

这里有一个我用来做这个的类别。它只会以十六进制形式给出数据中的所有字符,没有换行或其他任何东西。

@implementation NSData (NSData_Conversion)

#pragma mark - String Conversion
- (NSString *)hexadecimalString
{
    /* Returns hexadecimal string of NSData. Empty string if data is empty.   */
    
    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
    
    if (!dataBuffer)
    {
        return [NSString string];
    }
    
    NSUInteger          dataLength  = [self length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i)
    {
        [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }
    
    return [NSString stringWithString:hexString];
}

@end

3

最简单的解决方案是遍历NSData的每个字节,并从中构建NSString。使用[yourData bytes]访问字节,并将字符串构建为NSMutableString。

下面是通过实现NSData的类别来演示的例子:

interface NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces;
@end

@implementation NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces
{
    const unsigned char* bytes = (const unsigned char*)[self bytes];
    NSUInteger nbBytes = [self length];
    //If spaces is true, insert a space every this many input bytes (twice this many output characters).
    static const NSUInteger spaceEveryThisManyBytes = 4UL;
    //If spaces is true, insert a line-break instead of a space every this many spaces.
    static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
    const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
    NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);

    NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
    for(NSUInteger i=0; i<nbBytes; ) {
        [hex appendFormat:@"%02X", bytes[i]];
        //We need to increment here so that the every-n-bytes computations are right.
        ++i;

        if (spaces) {
            if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
            else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
        }
    }
    return [hex autorelease];
}
@end





  NSData* data = ...
NSString* hex = [data hexRepresentationWithSpaces_AS:YES];

2

这是通过整数运算进行的转换:

-(NSString*)hex:(NSData*)data{
     NSMutableData *result = [NSMutableData dataWithLength:2*data.length];
     unsigned const char* src = data.bytes;
     unsigned char* dst = result.mutableBytes;
     unsigned char t0, t1;

     for (int i = 0; i < data.length; i ++ ) {
          t0 = src[i] >> 4;
          t1 = src[i] & 0x0F;

          dst[i*2] = 48 + t0 + (t0 / 10) * 39;
          dst[i*2+1] = 48 + t1 + (t1 / 10) * 39;
     }

     return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
}

1
好的,我终于弄清楚了39'a' - '0' - 10 - Cœur

0

这个答案是在运行于Xcode 10 Playground的Swift 4.2中。

import Foundation

let d = Data(bytes: [0x3f, 0x09, 0x0a, 0xa3, 0x01])
let s:String = d.compactMap({ String(format: "%02x ", $0) }).joined()
print(s)

这是输出结果:

3f 09 0a a3 01 

0

Swift 2 版本

private let kHexChars = Array("0123456789abcdef".utf8) as [UInt8];

extension NSData {

    public func hexString() -> String {
        guard length > 0 else {
            return ""
        }

        let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: length)
        var output = [UInt8](count: length*2 + 1, repeatedValue: 0)
        var i: Int = 0
        for b in buffer {
            let h = Int((b & 0xf0) >> 4)
            let l = Int(b & 0x0f)
            output[i++] = kHexChars[h]
            output[i++] = kHexChars[l]
        }

        return String.fromCString(UnsafePointer(output))!
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接