用十六进制值替换NSData中的字节

时间:2014-11-27 17:07:13

标签: cocoa

用户在文本框中输入0到5000之间的值。我需要将dataToSend中的字节4和5替换为文本框中的十六进制值。例如,如果用户输入250,我将其转换为00FA。在dataToSend中,将0x03替换为0x00,将0xEB替换为0xFA。 str和str2在那里,所以我可以看到数据。它们之间存在差异,我不知道哪个是正确的。

- (IBAction)handleConfig1DelayMoveChange:(id)sender
  {
    NSString *tmp;
    int value;
    tmp = [txtDelayBeforeMove1 stringValue];
    NSString *hex = [NSString stringWithFormat:@"0x%04lX",(unsigned long)[tmp integerValue]];
    NSString *hex1 = [NSString stringWithFormat:@"%04lX",(unsigned long)[tmp integerValue]];
   dataToSend = [NSMutableData dataWithBytes:&((char[6]){0x51,0x04,0x02,0x03,0xEB,0x0D}) length:6];
   NSString *str = [[NSString alloc] initWithData:dataToSend encoding:NSASCIIStringEncoding];
   NSString *str2 = [NSString stringWithFormat:@"%.*s", [dataToSend length], [dataToSend bytes]];
   tmp = @"";
   tmp = [hex1 substringWithRange:NSMakeRange(1,2)];
   value = [tmp intValue];
   [dataToSend replaceBytesInRange: NSMakeRange(3,1) withBytes: &value];
   str2 = [NSString stringWithFormat:@"%.*s", [dataToSend length], [dataToSend bytes]];
}

1 个答案:

答案 0 :(得分:0)

这很有效。欢迎提出意见和改进建议。 displayhexStr用于在调试时验证更改。

- (IBAction)handleConfig1DelayMoveChange:(id)sender
  {
    NSString *tmp;
    int i;
    if([txtDelayBeforeMove1 intValue] < 0 || [txtDelayBeforeMove1 intValue] > 5000)
    {
      [self showAlert:@"Value must be between 0 and 5000"];
      return;
    }
    tmp = [txtDelayBeforeMove1 stringValue];
    NSString *hex1 = [NSString stringWithFormat:@"%04lX",(unsigned long)[tmp integerValue]];
    dataToSend = [NSMutableData dataWithBytes:&((char[6]){0x51,0x04,0x02,0x03,0xEB,0x0D}) length:6];
    NSMutableString *displayhexStr =
    [NSMutableString stringWithCapacity:[dataToSend length]*2];
    for (i = 0; i < [dataToSend length]; i++) {
      [displayhexStr appendFormat:@"%02x ", dbytes[i]];
    }
    tmp = [hex1 substringWithRange:NSMakeRange(0,2)];
    NSScanner* scanner = [NSScanner scannerWithString:tmp];
    unsigned int intValue;
    [scanner scanHexInt:&intValue];
    unsigned char uc = (unsigned char) intValue;
    [dataToSend replaceBytesInRange: NSMakeRange(3,1) withBytes: &uc];
    displayhexStr = [NSMutableString stringWithCapacity:[dataToSend length]*2];
    for (i = 0; i < [dataToSend length]; i++)
    {
      [displayhexStr appendFormat:@"%02X ", dbytes[i]];
    }
    tmp = [hex1 substringWithRange:NSMakeRange(2,2)];
    scanner = [NSScanner scannerWithString:tmp];
    [scanner scanHexInt:&intValue];
    uc = (unsigned char) intValue;
    [dataToSend replaceBytesInRange: NSMakeRange(4,1) withBytes: &uc];
    displayhexStr = [NSMutableString stringWithCapacity:[dataToSend length]*2];
    for (i = 0; i < [dataToSend length]; i++)
    {
      [displayhexStr appendFormat:@"%02X ", dbytes[i]];
    }
    [self send];
}