Revils
Revils

Reputation: 1508

Integer to character in Objective-C

I am trying to convert integers to characters and vice versa in Objective-C.

For example if I try to convert the numbers;

171, 154, 140 and 139 to a character, I respectively get; '«öåã', however I expected '«šŒ‹' (According to ASCII, «öåã is respectively 171, 246, 229, 227). Does anyone have a clue why this is the case?

I am using the following:

char c = number; //also tried char *c and unichar c.

Besides that, I also tried the following function, from another stackoverflow question:

+(NSString *)ConvertWithEncoding:(NSInteger) integer{
    char chars[2];
    int len = 1;

    if(integer > 127){
        chars[0] = (integer >> 8) & (1 << 8) - 1;
        chars[1] = integer & (1 << 8) - 1;
        len = 2;
    }else{
        chars[0] = integer;
    }

    //Also tried with NSUTF8Encoding, always resulted in nil.
    return [[NSString alloc] initWithBytes:chars length:len encoding:NSASCIIEncoding];
}

@Edit

I am using the following code to append the individual characters to a NSString:

[NSString stringWithFormat:@"%@%c", data, c];

Upvotes: 0

Views: 710

Answers (2)

Martin R
Martin R

Reputation: 539705

171, 154, 140 and 139 to a character, ... however I expected '«šŒ‹'

Apparently you are looking for the Windows-1252 encoding:

+(NSString *)convertWithEncoding:(NSInteger) integer {
    uint8_t byte = integer; 
    return [[NSString alloc] initWithBytes:&byte length:1 encoding: NSWindowsCP1252StringEncoding];
}

Example:

NSLog(@"%@", [MyClass convertWithEncoding:171]); // «
NSLog(@"%@", [MyClass convertWithEncoding:154]); // š
NSLog(@"%@", [MyClass convertWithEncoding:140]); // Œ
NSLog(@"%@", [MyClass convertWithEncoding:139]); // ‹

Upvotes: 1

JohnMorrison
JohnMorrison

Reputation: 504

You need to reverse your byte order for Intel:

-(NSString *)ConvertWithEncoding:(NSInteger) integer {

    char chars[2];
    int len = 1;
    int newVal = CFSwapInt16HostToBig(integer);

    if(newVal > 127){
        chars[0] = (newVal >> 8) & (1 << 8) - 1;
        chars[1] = newVal & (1 << 8) - 1;
        len = 2;
    }else{
        chars[0] = newVal;
    }



    //Also tried with NSUTF8Encoding, always resulted in nil.
    return [[NSString alloc] initWithBytes:chars length:len encoding:NSASCIIStringEncoding];
}

Upvotes: 0

Related Questions