【问题标题】:Integer to character in Objective-CObjective-C中的整数到字符
【发布时间】:2016-07-31 15:58:08
【问题描述】:

我正在尝试在 Objective-C 中将整数转换为字符,反之亦然。

例如,如果我尝试转换数字;

171、154、140和139到一个字符,我分别得到; '«öåã',但我希望是 '«šŒ‹'(根据 ASCII,«öåã 分别是 171、246、229、227)。有人知道为什么会这样吗?

我正在使用以下内容:

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

除此之外,我还尝试了以下函数,来自另一个 stackoverflow 问题:

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

@编辑

我正在使用以下代码将单个字符附加到 NSString:

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

【问题讨论】:

  • 您说您将整数转换为单个字符,但将结果写为'«öåã',它看起来像一个字符串。你能展示你用来转换所有四个字符并显示结果的代码吗?这应该可以帮助人们帮助你。
  • 我已将其添加到问题中,只需使用 stringWithFormat 添加即可。但是,例如,当转换整数 154 时,'ö' 在 char c

标签: objective-c unicode type-conversion ascii


【解决方案1】:

171、154、140 和 139 到一个字符,...但是我期望 '«šŒ‹'

显然您正在寻找Windows-1252 编码:

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

例子:

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

【讨论】:

    【解决方案2】:

    您需要颠倒 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];
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 2012-12-28
      • 2013-08-02
      • 2012-01-29
      • 2015-07-23
      • 1970-01-01
      • 2011-02-17
      • 2011-10-21
      • 2015-07-08
      相关资源
      最近更新 更多