如何在swift中将字节数组转换为base64字符串?

时间:2017-01-06 08:54:41

标签: ios arrays swift pointers base64

以下是我在目标C中的示例代码

 -(NSString *)getImageString : (unsigned char *) charValue : (unsigned long) sizeOfBytes {                   

    uint8_t commandbyte[]={ };          

    uint8_t _allBytes[(sizeOfBytes + sizeof(commandbyte))];
    memcpy(_allBytes, charValue, sizeOfBytes);

    NSMutableData *ImageData = [[NSMutableData alloc]init];
    [ImageData appendBytes:_allBytes length:sizeof(_allBytes)];

    NSString *base64String=[self base64forData:ImageData];

    return base64String;                     
}                  

- (NSString*)base64forData:(NSData*)theData {           

    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;

        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] = table[(value >> 18) & 0x3F];
        output[theIndex + 1] = table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

在此示例中,我曾使用bytes然后使用sizeOfBytesappendBytes获取NSMutableData

以下方法用于将data转换为base64

- (NSString*)base64forData:(NSData*)theData

在目标C中它非常简单,但是当我在swift中尝试使用UnsafeMutablePointerUnsafePointer等指针的其他概念时。

如何转换为swift 3.0 ??

你能不能请教我快速使用指针

2 个答案:

答案 0 :(得分:7)

您可以使用以下方式将bytes数组转换为base64String

let base64String = data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))

答案 1 :(得分:0)

快速5使用以下方法将字节数组转换为base64String

示例1

result = json['result']
set_point = 0.0 

for res in result:
   if 'SetPoint' in res:
        set_point = res['SetPoint']

输出示例1

    let plainText = "Hello world!"
    print("Plain Text:- ", plainText)
    print("Base64String:- ", Array(plainText.utf8).toBase64()!)

示例2

Plain Text:-  Hello world!
Base64String:-  SGVsbG8gd29ybGQh

输出示例2

    let ivBase64str = "AbcnmWikMkW4c7+mHtwtfw=="
    let iv = [UInt8](base64: ivBase64str)
    print("BytesArray ", iv)
    print("Base64String ", iv.toBase64()!)