Преобразование NSString в Hex - PullRequest
2 голосов
/ 25 ноября 2010

Я много читал о том, как преобразовать строку в шестнадцатеричное значение. Вот что я нашел для достижения этой цели:

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

Это вернуло некоторые "интересные" результаты, и после прочтения я нашел пост, в котором упоминалось это

"Вы передаете указатель на объект, представляющий числовое значение, а не собственно числовое значение."

Поэтому я заменил 192 вместо «midiValue», и он сделал то, что ожидал.

Как бы передать строковое значение, а не указатель?

замедление среднего значения:

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

Ответы [ 2 ]

4 голосов
/ 25 ноября 2010

Вам, вероятно, нужно сделать что-то вроде этого:

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];
}

Надеюсь, это поможет.

2 голосов
/ 18 сентября 2012

, если вы возитесь с простым приложением iPhone в XCode, используя симулятор iPhone 5.1, тогда это полезно:

//========================================================
// 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]];

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...