next up previous FITS Documents
Next: ASCII Decoding Up: Example C Code Previous: Accumulating the Checksum

ASCII Encoding

The byte alignment is permuted one byte forward for FITS to left justify the string value starting in column 12. A similar production routine might receive the desired number of bytes to permute as an argument.

unsigned exclude[13] = { 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
                         0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60 };

int offset = 0x30;                          /* ASCII 0 (zero) */

char_encode (value, ascii)
unsigned int value;
char *ascii;
{
        int byte, quotient, remainder, ch[4], check, i, j, k;
        char asc[32];

        for (i=0; i < 4; i++) {
            byte = (value << 8*i) >> 24;    /* each byte becomes four */
            quotient = byte / 4 + offset;
            remainder = byte % 4;
            for (j=0; j < 4; j++)
                ch[j] = quotient;
            ch[0] += remainder;

            for (check=1; check;)           /* avoid ASCII punctuation */
                for (check=0, k=0; k < 13; k++)
                    for (j=0; j < 4; j+=2)
                        if (ch[j]==exclude[k] || ch[j+1]==exclude[k]) {
                            ch[j]++;
                            ch[j+1]--;
                            check++;
                        }

            for (j=0; j < 4; j++)           /* assign the bytes */
                asc[4*j+i] = ch[j];
        }

        for (i=0; i < 16; i++)              /* permute the bytes for FITS */
            ascii[i] = asc[(i+15)%16];

        ascii[16] = 0;
}