How to convert NSString to HEX String in Objective-C?

后端 未结 1 418
萌比男神i
萌比男神i 2021-01-23 15:13

I have a NSString with string like \"hello\".

Now I want to convert the string into another NSString object which shows a hex string. How to do that ?

1条回答
  •  抹茶落季
    2021-01-23 15:28

    Hmm - apart from the obvious which can be found elsewhere - how about something like:

        NSString * str = @"Hello World";
    
        NSString * hexStr = [NSString stringWithFormat:@"%@",
                             [NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding] 
                                            length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
    
        for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil]) 
            hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
    
        NSLog(@"%@", hexStr);
    

    which should give an output like

        48656c6c6f20576f726c64
    

    Optimising this is left as an exercise to the reader :) :)

    0 讨论(0)
提交回复
热议问题