WrightsCS WrightsCS - 1 year ago 91
Objective-C Question

Convert time_t to little endian?

I am converting

to Unix time. Problem is, I need to convert this to little endian so that it can be sent over Bluetooth; but I have no idea how to convert
to little endian.

What I have so far:

time_t t = [date timeIntervalSince1970];

NSMutableData * date = [[NSMutableData alloc] init];
[data appendBytes:&t length:sizeof(t)];

What I get:

0x10603854 // Fri, 15 Sep 1978 21:02:12 GMT

What I need:

0x54386010 // Fri, 10 Oct 2014 22:39:12 GMT

Answer Source

Not the most elegant way.

NSMutableData *time_ = [[NSMutableData alloc] init];
time_t t = [date timeIntervalSince1970];
[time_ appendBytes:&t length:4];

unsigned char *bytePtr = (unsigned char *)[time_ bytes];
NSString* _time = [NSString stringWithFormat:@"%02X%02X%02X%02X", bytePtr[3], bytePtr[2], bytePtr[1], bytePtr[0]];

for (i = 0; i < 4; i++)
    if (_time.length > i*2)
        byte_chars[0] = [_time characterAtIndex:i*2];
        byte_chars[1] = [_time characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];

NSLog(@"_time_data %@", _time);


2014-10-13 16:54:59.766 wrightscs[20810:2929687] _time_data <543c4a31>

Timestamp Converted:

Hex time: 543c4a31

GMT: Mon, 13 Oct 2014 21:54:57 GMT

Your time zone: October 13, 2014 at 4:54:57 PM CDT

Decimal timestamp/epoch: 1413237297


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download