You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C/C新手求助:字符串转ByteArray及数据转换计算实现

Hey there! As someone who’s been through the early days of Objective-C/C string and byte handling, I know how tricky these conversions can be. Let’s walk through a complete implementation that matches the Java logic you outlined.


First, Define Required Constants

We’ll start with two core arrays that map to DTC prefixes and hex characters:

// Maps high 2 bits to DTC prefix letters: 0=P, 1=C, 2=B, 3=U
const char *dtcLetters = "PCBU";
// Hex character lookup for 4-bit values
const char *hexArray = "0123456789ABCDEF";

Implement hexStringToByteArray

Objective-C doesn’t have a native byte type, so we’ll use uint8_t (unsigned 8-bit integer, which aligns with Java’s byte range for DTC use cases). Here’s both Objective-C and pure C implementations:

Objective-C Version

- (NSData *)hexStringToByteArray:(NSString *)hexString {
    // Validate input: hex strings must have an even length
    NSAssert(hexString.length % 2 == 0, @"Hex string must contain an even number of characters");
    
    NSUInteger byteCount = hexString.length / 2;
    uint8_t *bytes = malloc(byteCount * sizeof(uint8_t));
    if (!bytes) return nil;
    
    for (NSUInteger i = 0; i < byteCount; i++) {
        NSString *byteSubstring = [hexString substringWithRange:NSMakeRange(i*2, 2)];
        NSScanner *scanner = [NSScanner scannerWithString:byteSubstring];
        unsigned int hexValue;
        [scanner scanHexInt:&hexValue];
        bytes[i] = (uint8_t)hexValue;
    }
    
    NSData *byteData = [NSData dataWithBytesNoCopy:bytes length:byteCount freeWhenDone:YES];
    return byteData;
}

Pure C Version

size_t hexStringToByteArray(const char *hexString, uint8_t **outBytes) {
    if (!hexString || !outBytes) return 0;
    
    size_t strLength = strlen(hexString);
    if (strLength % 2 != 0) return 0; // Invalid hex string length
    
    size_t byteCount = strLength / 2;
    *outBytes = malloc(byteCount * sizeof(uint8_t));
    if (!*outBytes) return 0;
    
    for (size_t i = 0; i < byteCount; i++) {
        char byteStr[3] = {hexString[i*2], hexString[i*2+1], '\0'};
        (*outBytes)[i] = (uint8_t)strtoul(byteStr, NULL, 16);
    }
    
    return byteCount;
}

Core DTC Extraction Logic

This is the main logic that matches your Java workflow: convert the working data, extract bit values, build DTC strings, and collect results.

- (NSArray<NSString *> *)extractDTCsFromWorkingData:(NSString *)workingData {
    NSMutableArray *codes = [NSMutableArray array];
    
    // Convert working data hex string to byte array
    NSData *byteData = [self hexStringToByteArray:workingData];
    if (!byteData) return codes;
    
    uint8_t *bytes = (uint8_t *)byteData.bytes;
    NSUInteger dataLength = byteData.length;
    
    // Iterate through each byte (adjust index logic if you need specific positions)
    for (NSUInteger i = 0; i < dataLength; i++) {
        uint8_t b1 = bytes[i];
        
        // Extract high 2 bits for ch1 (shift right 6, mask with 0x03 to keep only 2 bits)
        uint8_t ch1 = (b1 >> 6) & 0x03;
        // Extract next 2 bits for ch2 (shift right 4, mask with 0x03)
        uint8_t ch2 = (b1 >> 4) & 0x03;
        
        // Extract the required substring from workingData (adjust range to match your Java logic)
        // Assumption: workingData is hex, so each byte = 2 chars; substring starts after current byte's chars
        NSString *subStr = @"";
        if (i*2 + 2 + 4 <= workingData.length) {
            subStr = [workingData substringWithRange:NSMakeRange(i*2 + 2, 4)];
        }
        
        // Build the DTC string
        NSString *dtc = [NSString stringWithFormat:@"%c%c%@", dtcLetters[ch1], hexArray[ch2], subStr];
        
        // Check for termination condition or collect the DTC
        if ([dtc isEqualToString:@"P0000"]) {
            return codes; // Return immediately if we hit P0000
        } else {
            [codes addObject:dtc];
        }
    }
    
    return codes;
}

Key Details for Newbies

  • Bitwise Operations: (b1 >> 6) & 0x03 shifts the byte right 6 positions (moving the high 2 bits to the lowest position) then uses 0x03 (binary 00000011) to isolate those 2 bits.
  • Hex String Validation: The NSAssert ensures your input hex string is valid—you can replace this with error handling for production code.
  • Substring Adjustment: The substring range in the example assumes you need 4 characters (2 bytes) after the current byte. Adjust the NSMakeRange parameters to match exactly what your Java code does.

Usage Example

NSString *sampleWorkingData = @"001234567890ABCDEF";
NSArray *extractedDTCs = [self extractDTCsFromWorkingData:sampleWorkingData];
NSLog(@"Extracted DTC Codes: %@", extractedDTCs);

内容的提问来源于stack exchange,提问作者user9252797

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:27:16