6

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

A function should return hex value as:

5361792048656c6c6f20746f204d79204c6974746c6520467269656e64

Eric Aya
  • 69,000
  • 34
  • 174
  • 243
Ameet Dhas
  • 2,440
  • 4
  • 23
  • 38

3 Answers3

8

Swift 4, Swift 3

let hex: String = "ABC".unicodeScalars.filter { $0.isASCII } .map { String(format: "%X", $0.value) } .joined() print(hex) // correctly yields 414243

smat88dd
  • 1,858
  • 1
  • 20
  • 37
3

You can do this like,

NSString *str = @"Say Hello to My Little Friend";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"data %@",data);

Optput : data <53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>

Swift:

 let string = "Say Hello to My Little Friend"
 let data = string.dataUsingEncoding(NSUTF8StringEncoding)

Swift 3:

 let string = "Say Hello to My Little Friend"
 let data = string.data(using: String.Encoding.utf8)
José
  • 2,883
  • 1
  • 26
  • 40
Ketan Parmar
  • 26,610
  • 9
  • 47
  • 70
2

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:)

Ronak Chaniyara
  • 5,225
  • 3
  • 23
  • 50