/* * aencode.c * * Copyright 1995 The Ohio State University. * * Tom Sanfilippo * August 27, 1995 */ #include #include #include "aencode.h" static char encoding[65] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz()"; int bin2ascii(char *data_in, int data_in_len, char **data_out) { int size, current_bit_size,value; int i,j,k,l,m = 0; int whole_blocks,additional_last_bytes; union { struct { unsigned int base64_0 : 6; unsigned int base64_1 : 6; unsigned int base64_2 : 6; unsigned int base64_3 : 6; } cvt0; unsigned char base256[3]; } cvtr; whole_blocks = data_in_len / 3; additional_last_bytes = data_in_len % 3; current_bit_size = data_in_len * 8; size = (current_bit_size / 6) + ((current_bit_size % 6) ? 1 : 0); if (data_out != NULL) { *data_out = (char *)malloc(size + 1); if (*data_out != NULL) { for (i = 0; i < whole_blocks + (additional_last_bytes > 0 ? 1 : 0); i++) { memset(&cvtr, 0, 3); j = (i < whole_blocks ? 3 : additional_last_bytes); memcpy(&cvtr, data_in + (i * 3), j); k = (i < whole_blocks ? 4 : j * 4 / 3 + (((j * 4) % 3) ? 1 : 0)); for (l = 0; l < k; l++) { switch (l) { case 0: value = cvtr.cvt0.base64_0; break; case 1: value = cvtr.cvt0.base64_1; break; case 2: value = cvtr.cvt0.base64_2; break; case 3: value = cvtr.cvt0.base64_3; } (*data_out)[m] = encoding[value]; m++; } } (*data_out)[size] = '\0'; return size + 1; } } return 0; } int ascii2bin(char *data_in, char **data_out) { int data_in_len, size, current_bit_size, value; int i,j,k,l,m = 0; int whole_blocks,additional_last_bytes; union { struct { unsigned int base64_0 : 6; unsigned int base64_1 : 6; unsigned int base64_2 : 6; unsigned int base64_3 : 6; } cvt0; unsigned char base256[3]; } cvtr; data_in_len = strlen(data_in); current_bit_size = 6 * data_in_len; size = (current_bit_size / 8); whole_blocks = size / 3; additional_last_bytes = size % 3; if (data_out != NULL) { *data_out = (char *)malloc(size); if (*data_out != NULL) { for (i = 0; i < whole_blocks + (additional_last_bytes > 0 ? 1 : 0); i++) { memset(&cvtr, 0, 3); j = (i < whole_blocks ? 3 : additional_last_bytes); k = (i < whole_blocks ? 4 : j * 4 / 3 + (((j * 4) % 3) ? 1 : 0)); for (l = 0; l < k; l++) { if (!(m < data_in_len)) break; value = strchr(encoding, data_in[m]) - encoding; m++; switch (l) { case 0: cvtr.cvt0.base64_0 = value; break; case 1: cvtr.cvt0.base64_1 = value; break; case 2: cvtr.cvt0.base64_2 = value; break; case 3: cvtr.cvt0.base64_3 = value; } } memcpy(*data_out + (i * 3), &cvtr, j); } return size; } } return 0; }