C 實現base64編碼 1

2022-03-22 07:18:02 字數 1826 閱讀 6523

下面的**是php裡面的base64編碼邏輯,確實比我之前的要美觀很多,我只是簡單的用c++的類進行了一下封裝,刪除了一些沒用的邏輯,基本上還是原來php的**:

#include #include 

#include

using

namespace

std;

class

base64;

unsigned

char * base64::encode(const unsigned char *str, int length, int &ret_length) /*

;

const unsigned char *current =str;

unsigned

char *p;

unsigned

char *result;

result = new unsigned char[(length+2)/3*4

]; p =result;

if (length < 0

)

while (length > 2)

/*now deal with the tail end of things

*/if (length != 0

) else

}ret_length = (int)(p -result);

*p = '\0'

;

return

result;

}unsigned

char * base64::decode(const unsigned char *str, int length, int &ret_length) /*

;

const unsigned char *current =str;

int ch, i = 0, j = 0

, k;

/*this sucks for threaded environments

*/unsigned

char *result;

result = new unsigned char

[length];

/*run through the whole string, converting as we go

*/while ((ch = *current++) != '

\0' && length-- > 0

)

continue

; }

ch =base64_reverse_table[ch];

if (ch < 0 || ch == -1)

else

if (ch == -2

)

switch(i % 4

) i++;

cout

<< "

result ==

"<< result <}

k =j;

/*mop things up if we ended on a boundary

*/if (ch ==base64_pad)

}if(ret_length)

result[j] = '\0'

;

return

result;

}int

main()

上面的**對php原始碼中的邏輯做了優化,刪除了decode方法中判斷結尾的「=」號時多餘的邏輯,以免干擾視線。具體刪除的**參照php原始碼中ext/standard/base64.c

base64編碼實現

package com.ls.hfvj 思路 base64只有64個字元,因此只需要6個二進位制位來表示 實現 每3個位元組為一組湊4個base64字元。多餘乙個位元組補4個0bit位 共12位 湊成2個base64字元 多餘兩個位元組補2個bit位 共18位 湊成3個base64字元。為了知道新增...

base64編碼 動畫演示 Base 64 編碼

base64 是一種十分流行的編碼方式,僅僅使用 64 個字元加等號 就可以以文字的形式表示所有的二進位制資料了,因為它能夠把二進位制格式通過編碼轉換成可見字元,所有我們就可以通過的把二進位制格式比如,檔案等通過 base64 編碼然後通過文字的形式共享出去,是不是很神奇呀。把輸入的資料轉換成 二進...

php實現base64編碼

工作需要,想弄乙個加密的串,就想仿照base64的編碼方式,寫乙個加密的方法,所以就有了下面這個用php實現的base64的 base64 編碼 解碼 author liruixing class base64 bin bin ord str if i 1 3 0 if len 3 1 else i...