【问题标题】:Objective - C : unsigned int to base64目标-C:无符号整数到base64
【发布时间】:2015-07-01 01:42:35
【问题描述】:

我的服务器开发人员要求我使用以下规则向他们发送一些用 base64 编码的数据:

  1. 大端字节序
  2. 没有额外的零字节
  3. base64 字符串
例如: 10005000 → «mKol» 1234567890 → «SZYC0g»

我做了一些意大利面条式的代码,它的工作。但也许有人有更优雅的解决方案?

+ (NSString*)encodeBigEndianBase64:(uint32_t)value {

    char *bytes = (char*) &value;
    int len = sizeof(uint32_t);

    char *reverseBytes = malloc(sizeof(char) * len);
    unsigned long index = len - 1;

    for (int i = 0; i < len; i++)
        reverseBytes[index--] = bytes[i];

    int offset = 0;

    while (reverseBytes[offset] == 0) {
        offset++;
    }

    NSData *resultData;

    if (offset > 0) {

        int truncatedLen = (len - offset);
        char *truncateBytes = malloc(sizeof(char) * truncatedLen);

        for (int i = 0; i < truncatedLen ; i++)
            truncateBytes[i] = reverseBytes[i + offset];

        resultData = [NSData dataWithBytes:truncateBytes length:truncatedLen];
        free(truncateBytes);

    } else {

        resultData = [NSData dataWithBytes:reverseBytes length:len];
    }

    free(reverseBytes);

    return [[resultData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] stringByReplacingOccurrencesOfString:@"=" withString:@""];

}

稍微改进的解决方案(感谢 zaph):

+ (NSString*)encodeBigEndianBase64:(uint32_t)value {

uint32_t swappedValue = CFSwapInt32HostToBig(value);

char *swappedBytes = (char*) &swappedValue;
int len = sizeof(uint32_t);

int offset = 0;

while (swappedBytes[offset] == 0) {
    offset++;
}

NSData *resultData;

if (offset > 0) {

    int truncatedLen = (len - offset);
    char *truncateBytes = malloc(sizeof(char) * truncatedLen);

    for (int i = 0; i < truncatedLen ; i++)
        truncateBytes[i] = swappedBytes[i + offset];

    resultData = [NSData dataWithBytes:truncateBytes length:truncatedLen];
    free(truncateBytes);

} else {

    resultData = [NSData dataWithBytes:swappedBytes length:len];
}

return [[resultData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] stringByReplacingOccurrencesOfString:@"=" withString:@""];

}

【问题讨论】:

    标签: objective-c base64


    【解决方案1】:

    对于字节序转换,请使用htons()htonl()ntohs()ntohl()

    网络字节顺序是bigendian

    `htons()` // host to network short
    `htonl()` // host to network ling
    `ntohs()` // network to host long
    `ntohl()` // network to host long
    

    这些在 endan.h 中定义

    另见Byte-Order Utilities Reference

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2018-08-18
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2015-12-10
      • 2015-02-24
      • 2012-01-09
      相关资源
      最近更新 更多