Shamsudheen TK
Shamsudheen TK

Reputation: 31339

Convert GUID to NSString - ObjectiveC

I have defined a GUID structure as below

typedef struct _GUID {
    unsigned long  Data1;
    unsigned short Data2;
    unsigned short Data3;
    unsigned char  Data4[ 8 ];

} GUID;

I’m trying to convert it to NSString. However, I’m getting the reversed values for the first three (long, short,short). It may be due to the Big-endian.

Example:

 GUID testGUID = { 0x865f82d0, 0x3303, 0x403d, { 0xbf, 0xcd, 0xeb, 0xb2, 0xde, 0xd9, 0xa0, 0x69 } };
 NSUUID *uuid = [[NSUUID alloc] initWithUUIDBytes:(const unsigned char*)&testGUID];
 NSString *uuidString = [uuid UUIDString];
 NSLog(@"%@", uuidString);

Output: D0825F86-0333-3D40-BFCD-EBB2DED9A069

Expected: 865F82D0-3303-403D-BFCD-EBB2DED9A069

let me know Is there a way to correct this. Any help on this is much appreciated.

Upvotes: 1

Views: 487

Answers (1)

Shamsudheen TK
Shamsudheen TK

Reputation: 31339

@borrrden comment fixed the issue.

Here is the solution.

GUID testGUID = { 0x865f82d0, 0x3303, 0x403d, { 0xbf, 0xcd, 0xeb, 0xb2, 0xde, 0xd9, 0xa0, 0x69 } };

testGUID.Data1 = NTOHL(testGUID.Data1);
testGUID.Data2 = NTOHS(testGUID.Data2);
testGUID.Data3 = NTOHS(testGUID.Data3);

NSUUID *uuid = [[NSUUID alloc] initWithUUIDBytes:(const unsigned char*)&testGUID];
NSString *uuidString = [uuid UUIDString];
NSLog(@"%@", uuidString)

Upvotes: 1

Related Questions