将INT转换为十六进制字符串以通过BLE发送

时间:2014-11-17 22:15:57

标签: objective-c nsmutabledata

我正在尝试将几个'int'值转换为十六进制,以便它们可以通过蓝牙作为命令发送。

我尝试了很多东西,但是当我用不同的方法得到相同的结果时,我无法通过BLE发送所需的结果,以便设备识别该命令。

- (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
}

一些不正确的结果

// command = [NSString stringWithFormat:@"0212%02x25%02x25%02x%02x25", value1, value2, value3, value4];
// <02122de2 52b25320 72>

2 个答案:

答案 0 :(得分:3)

在这里,有什么可以激励你:

我制作了NSData的分类方法(您可能会在其他地方找到此代码,不记得确切地说,它不是我的,有关于SO的一些问题,但我认为我混合了各种答案),并补充说:

+(NSData *)dataWithStringHex:(NSString *)string
{
    NSString *cleanString;
    cleanString = [string stringByReplacingOccurrencesOfString:@"<" withString:@""];
    cleanString = [cleanString stringByReplacingOccurrencesOfString:@">" withString:@""];
    cleanString = [cleanString stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSInteger length = [cleanString length];
    uint8_t buffer[length/2];
    for (NSInteger i = 0; i < length; i+=2)
    {
        unsigned result = 0;
        NSScanner *scanner = [NSScanner scannerWithString:[cleanString substringWithRange:NSMakeRange(i, 2)]];
        [scanner scanHexInt:&result];
        buffer[i/2] = result;
    }
    return  [[NSMutableData alloc] initWithBytes:&buffer length:length/2];
}

我有时会用它来调试。这解释了cleanString用于删除空格的事情,&#34;&lt;&#34;和&#34;&gt;&#34;。 换句话说,如果您有NSString 012345,则会NSData 012345。非常方便。

所以请与你一起检查样品(顺便说一句,它在stringWithFormat:中缺少&#34; 0&#34;)

int value1 = 734;
int value2 = 43;
int value3 = 50;
int value4 = 7;

NSString *command = [NSString stringWithFormat:@"02102%02x25%02x25%02x%02x25", value1, value2, value3, value4];
NSLog(@"Command: %@", command);
NSData *data = [NSData dataWithStringHex:command];
NSLog(@"Data: %@", data);

输出:

  

命令:021022de252b25320725
  数据:&lt; 021022de 252b2532 0725&gt;

答案 1 :(得分:2)

- (void)sendValues:(int)value1 value2:(int)value2 value3:(int)value3 value4:(int)value4
{

    uint8_t command [] = {0x02, 0x12,0x02,value1,0x25,value2, 0x25, value3, value4, 0x25};
    NSData *data = [NSData dataWithBytes:command length:sizeof(command)];
}

数据包含<021202de 252b2532 0725>

也许这会让你开始。