Search code examples
cembeddeduuencode

Adding Null Padding to UUEncoder in C


I know I'm close to finishing this UUEncoder function; I'll be using it to communicate with an embedded device. But for my life, I can't figure out how to get the null padded characters inserted properly at the end.

I've been trying to follow the example here.

void encode(unsigned char fileData_Hex_String[], int hexDataCharCount)
{
    unsigned char UUE_Encoded_String[MAX_SIZE];
    unsigned char b[2];
    unsigned char d[3];
    int UUE_Encoded_String_Index = 0;

    hexDataCharCount =7;

    for(int hexDataIndex = 0;  hexDataIndex < hexDataCharCount; hexDataIndex)
    {
        // Load chars or nulls
        for (int i = 0; i < 3; ++i)
        {
            b[i] = fileData_Hex_String[hexDataIndex];
            printf("%i\n", (hexDataIndex - hexDataCharCount));
            if ((hexDataIndex - hexDataCharCount) > 0)
            {
                b[1] = '\n';
                b[2] = '\n';
                break;
            }
            hexDataIndex++;
        }


        // UUEncode
        d[0] = (((b[0] >> 2) & 0x3f) + ' ');
        d[1] = ((((b[0] << 4) | ((b[1] >> 4) & 0x0f)) & 0x3f) + ' ');
        d[2] = ((((b[1] << 2) | ((b[2] >> 6) & 0x03)) & 0x3f) + ' ');
        d[3] = ((b[2] & 0x3f) + ' ');

        // Put the UUEncoded chars into their own string.
        for (int i = 0; i < 4; i++)
        {
            UUE_Encoded_String[UUE_Encoded_String_Index] = d[i];
            printf(" 0x%2x \n", UUE_Encoded_String[UUE_Encoded_String_Index]);
            UUE_Encoded_String_Index++;
        }
    }
}

Everything works fine, except I get two unwanted characters at the end 0x48 and 0x2A.


Solution

  • \n is not a null it is a newline. If you put

    b[1] = 0;
    b[2] = 0;
    

    The last two bytes will be 0x20 0x20. But your code will be more flexible if you write the loop like this

    // Load chars or nulls
    for (i = 0; i < 3; ++i)
    {
        if (hexDataIndex < hexDataCharCount)
            b[i] = fileData_Hex_String[hexDataIndex];
        else
            b[i] = 0;
        hexDataIndex++;
    }