Skip to content

Instantly share code, notes, and snippets.

@JiapengLi
Last active November 11, 2017 04:50
Show Gist options
  • Select an option

  • Save JiapengLi/07298b79f0141944e7dcc24ebcc546dd to your computer and use it in GitHub Desktop.

Select an option

Save JiapengLi/07298b79f0141944e7dcc24ebcc546dd to your computer and use it in GitHub Desktop.
// https://tools.ietf.org/html/rfc4648
// https://en.wikipedia.org/wiki/Base32
const char base32_tab[32] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
int bin2base32hex(uint8_t *buf, int len, char *base32, bool pad)
{
int i, j, k, cnt = 0;
uint8_t val = 0;
int padnum;
padnum = 8-((len*8+4)/5)%8;
for(i=0, k=0; i<len; i++){
for(j=0; j<8; j++){
if( ( buf[i] & (0x80>>j) ) != 0 ){
val |= (0x10>>cnt);
}
cnt++;
if( cnt == 5 ){
base32[k] = base32_tab[val];
val = 0;
cnt = 0;
k++;
}
}
}
if( cnt > 0 ){
/* no padding */
base32[k] = base32_tab[val];
cnt = 0;
k++;
}
if(pad){
for(i=0; i<padnum; i++){
base32[k] = '=';
k++;
}
}
return k;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment