I am trying to convert several 'int' values to hex so that they can sent over bluetooth as a command.
I have tried numerous things, but while I get the same result with different methods, I cannot get the desired result to send over BLE so that the device recognizes the command.
- (void)sendValues:(int)value1 value2:(int)value2 value3:(int)value3 value4:(int)value4
{
// value1 = 734,
// value2 = 43
// value3 = 50
// value4 = 7
// this string should be constructed from the values passed through
// NSString * command = @"021202de343325353025203725";
NSMutableData * _data = [[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);
[_data appendBytes:&whole_byte length:1];
}
//<021202de 34332535 30252037 25> // the desired NSMutableData command
}
Some incorrect results
// command = [NSString stringWithFormat:@"0212%02x25%02x25%02x%02x25", value1, value2, value3, value4];
// <02122de2 52b25320 72>
Here, what can inspire you:
I made a category method of
NSData
(you may find this code elsewhere on SO, don't remember where exactly, it's not mine, there are a few questions about that in SO, but I think I mixed the various answers), adding this:I use it sometimes to debug. That explains the thing going with
cleanString
for removing the spaces, the "<" and the ">". In other words, if you have aNSString
012345
, it will make aNSData
of012345
. Pretty handy sometimes.So checking with you sample (by the way, it was missing a "0" in the
stringWithFormat:
):With output: