首页 > 代码库 > Base64编码详解

Base64编码详解

Base64编码过程:将二进制序列转换为Base64字符序列(ASCII码序列)。

 

一、标准Base64字符表

技术分享

 

二、Base64编码示例

编码字符串"Hello!!",输出结果"SGVsbG8hIQ=="

技术分享

 

三、Base64编码

原理:一个字节包括8位二进制, 然而字符表总共才64个字符,用6位二进制完全容纳64个字符,所以每6位二进制转换为对应的Base64字符。

编码过程:第一次读6位二进制,该子节剩余的2位转到下一次操作。恰好最少3个字节(24位)能转换成4个Base64字符,所以新数据的长度为原来数据3分之4倍。

特殊情况处理:当原来数据的字节数不是3的倍数时,如果除3余1时,规定在编码后添加2个"=",如果除3余2时,规定在编码后添加1个"="。

 

四、Base64编码自己实现

+(NSString*)base64fromData:(NSData*)originData
{
    const uint8_t* input = (const uint8_t*)[originData bytes];
    NSInteger originLength = [originData length];
    
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData* encodeData = http://www.mamicode.com/[NSMutableData dataWithLength:((originLength + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)encodeData.mutableBytes;
    
    NSInteger i;
    for (i=0; i < originLength; i += 3) {
        NSInteger value = http://www.mamicode.com/0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < originLength) {
                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) < originLength ? table[(value >> 6)  & 0x3F] : ‘=‘;
        output[theIndex + 3] = (i + 2) < originLength ? table[(value >> 0)  & 0x3F] : ‘=‘;
    }
    
    return [[NSString alloc] initWithData:encodeData encoding:NSASCIIStringEncoding];
}

 

五、NSData官方提供的Base64编码接口

/* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64 encoded NSString from the receiver‘s contents using the given options.
*/
- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64, UTF-8 encoded NSData from the receiver‘s contents using the given options.
*/
- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

 

Base64编码详解