Last active
August 29, 2015 14:27
-
-
Save flagoworld/8cf08ed6e2fa43b2e7c1 to your computer and use it in GitHub Desktop.
packing some data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSData *)build | |
{ | |
uint32_t type = _type; // 0 | |
uint32_t command = _command; // 3 | |
NSString *data = _data; // @"" | |
unsigned char byte = 0x00; // 0 | |
unsigned long size = sizeof(command) + sizeof(type) + data.length + sizeof(byte); // 9 | |
unsigned long totalSize = sizeof(uint32_t) + size; // 10 (including size uint32) | |
unsigned char bytes[totalSize]; | |
NSLog(@"Stats: %lu, %lu", size, totalSize); // Stats: 9, 13 | |
uint32_t b; | |
unsigned char *p; | |
// Size | |
b = htonl(size); | |
// memcpy(bytes, &b, sizeof(b)); | |
p = (unsigned char *)&b; | |
bytes[0] = p[0]; | |
bytes[1] = p[1]; | |
bytes[2] = p[2]; | |
bytes[3] = p[3]; | |
// Command | |
b = htonl(command); | |
memcpy(bytes + 4, &b, sizeof(b)); | |
// Type | |
b = htonl(type); | |
memcpy(bytes + 8, &b, sizeof(b)); | |
// Data | |
const char *dataBytes = [data UTF8String]; | |
for(UInt32 i = 0; i < data.length; ++i) | |
{ | |
bytes[i + 12] = dataBytes[i]; | |
} | |
bytes[totalSize - 1] = byte; | |
NSData *d = [NSData dataWithBytes:&bytes length:totalSize]; | |
NSMutableString *str = [NSMutableString new]; | |
for(UInt32 i = 0; i < totalSize; ++i) | |
{ | |
if(i < 12 || i == totalSize - 1) | |
{ | |
[str appendFormat:@"%i", bytes[i]]; | |
}else | |
{ | |
[str appendFormat:@"%c", bytes[i]]; | |
} | |
} | |
NSLog(@"Sending: %@", str); // Sending: 0009000300000 | |
return d; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment