How to convert a text string to hex string?

后端 未结 3 1941
一向
一向 2021-01-18 14:06

Lets say I have a text string : \"Say Hello to My Little Friend\"

A function should return hex value as:

5361792048656c6c6f20746f204d79204c6974746c6520467269

3条回答
  •  死守一世寂寞
    2021-01-18 15:10

    Couldn't able to write in swift, but in Objective-C below code is may be what you are looking for:

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

    Above code gives exact string as you given:

    5361792048656c6c6f20746f204d79204c6974746c6520467269656e64

    Hope it will help:)

提交回复
热议问题