将NSString转换为十六进制

时间:2010-11-25 17:52:41

标签: objective-c xcode core-data hex

我一直在阅读有关如何将字符串转换为十六进制值的大量内容。以下是我发现的目标:

NSString * hexString = [NSString stringWithFormat:@"%x", midiValue];

这返回了一些“有趣”的结果,在稍微阅读后,我发现了一篇提到这个的帖子

“您正在向表示数值的对象传递指针,而不是正确的数值。”

所以我用192代替了“midiValue”,它完成了我的预期。

我如何传递字符串值而不是指针?

midiValue的清除:

NSString *dMidiInfo = [object valueForKey:@"midiInformation"];
    int midiValue = dMidiInfo;

2 个答案:

答案 0 :(得分:4)

你可能需要这样做:

NSNumberFormatter *numberFormatter= [[NSNumberFormatter alloc] init];
int anInt= [[numberFormatter numberFromString:string ] intValue];

另外,我认为xcode文档中有一些示例代码用于在QTMetadataEditor示例中转换为十六进制值和从十六进制值转换。在MyValueFormatter类中。

+ (NSString *)hexStringFromData:(NSData*) dataValue{
    UInt32 byteLength = [dataValue length], byteCounter = 0;
    UInt32 stringLength = (byteLength*2) + 1, stringCounter = 0;
    unsigned char dstBuffer[stringLength];
    unsigned char srcBuffer[byteLength];
    unsigned char *srcPtr = srcBuffer;
    [dataValue getBytes:srcBuffer];
    const unsigned char t[16] = "0123456789ABCDEF";

    for (; byteCounter < byteLength; byteCounter++){
        unsigned src = *srcPtr;
        dstBuffer[stringCounter++] = t[src>>4];
        dstBuffer[stringCounter++] = t[src & 15];
        srcPtr++;
    }
    dstBuffer[stringCounter] = '\0';

    return [NSString stringWithUTF8String:(char*)dstBuffer];
}

+ (NSData *)dataFromHexString:(NSString*) dataValue{
    UInt32 stringLength = [dataValue length];
    UInt32 byteLength = stringLength/2;
    UInt32 byteCounter = 0;
    unsigned char srcBuffer[stringLength];
    [dataValue getCString:(char *)srcBuffer];
    unsigned char *srcPtr = srcBuffer;
    Byte dstBuffer[byteLength];
    Byte *dst = dstBuffer;
    for(; byteCounter < byteLength;){
        unsigned char c = *srcPtr++;
        unsigned char d = *srcPtr++;
        unsigned hi = 0, lo = 0;
        hi = charTo4Bits(c);
        lo = charTo4Bits(d);
        if (hi== 255 || lo == 255){
            //errorCase
            return nil;
        }
        dstBuffer[byteCounter++] = ((hi << 4) | lo);
    }
    return [NSData dataWithBytes:dst length:byteLength];
}

希望这有帮助。

答案 1 :(得分:2)

如果您使用iPhone 5.1模拟器在Xcode中搞乱一个简单的iPhone应用程序,那么这很有用:

//========================================================
// This action is executed whenever the hex button is
// tapped by the user.
//========================================================
- (IBAction)hexPressed:(UIButton *)sender 
{
   // Change the current base to hex.
   self.currentBase = @"hex";

   // Aquire string object from text feild and store in a NSString object
   NSString *temp = self.labelDisplay.text;

   // Cast NSString object into an Int and the using NSString method StringWithFormat
   // which is similar to c's printf format then output into hexidecimal then return
   // this NSString object with the hexidecimal value back to the text field for display
    self.labelDisplay.text=[NSString stringWithFormat:@"%x",[temp intValue]];

}
相关问题