-
Notifications
You must be signed in to change notification settings - Fork 3
/
NSData+Flip.mm
108 lines (85 loc) · 2.45 KB
/
NSData+Flip.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//
// NSData+Flip.m
// tetherKit
//
// Created by Kevin Bradley on 1/26/12.
// Copyright 2012 FireCore, LLC. All rights reserved.
//
#import "NSData+Flip.h"
static NSString *CYDHex(NSData *data, bool reverse) {
if (data == nil)
return nil;
size_t length([data length]);
uint8_t bytes[length];
[data getBytes:bytes];
char string[length * 2 + 1];
for (size_t i(0); i != length; ++i)
sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
return [NSString stringWithUTF8String:string];
}
static NSData *CYDataHex(NSData *data, bool reverse) {
if (data == nil)
return nil;
size_t length([data length]);
uint8_t bytes[length];
[data getBytes:bytes];
char string[length * 2 + 1];
for (size_t i(0); i != length; ++i)
sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
return [NSData dataWithBytes:string length:length];
}
static NSString *HexToDec(NSString *hexValue)
{
if (hexValue == nil)
return nil;
unsigned long long dec;
NSScanner *scan = [NSScanner scannerWithString:hexValue];
if ([scan scanHexLongLong:&dec])
{
return [NSString stringWithFormat:@"%llu", dec];
//NSLog(@"chipID binary: %@", finalValue);
}
return nil;
}
@implementation NSData (myAdditions)
+ (NSData *)dataFromStringHex:(NSString *)command
{
command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [command length]/2; i++) {
byte_chars[0] = [command characterAtIndex:i*2];
byte_chars[1] = [command characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[commandToSend appendBytes:&whole_byte length:1];
}
//NSLog(@"%@", commandToSend);
return [commandToSend autorelease];
}
- (NSData *)reverse
{
return [NSData dataFromStringHex:CYDHex(self, TRUE)];
}
- (NSString *)decimalString
{
NSString *stringData = CYDHex(self, TRUE);
return HexToDec(stringData);
}
-(NSData *) byteFlipped
{
NSMutableData *newData = [[NSMutableData alloc] init];
const char *_data = (char *)[self bytes];
int stringLength = [self length];
//NSLog(@"stringLength: %i", [self length]);
int x;
for( x=stringLength-1; x>=0; x-- )
{
char currentByte = _data[x];
//printf("%c,", _data[x]);
[newData appendBytes:¤tByte length:1];
}
return [newData autorelease];
}
@end