Thursday, August 31, 2006

Python

Convert .csv file to .c in a certain format

$ python this.py RESOURCE.CVS DESTINATION.c


#!/usr/bin/python
import os, sys

input_file = sys.stdin
output_file = sys.stdout
input_file = open( sys.argv[ 1 ] )
output_file = open( sys.argv[ 2 ], 'w' )

str1="""#ifdef EMBED
code //Needs to be placed in code memory for 2051
#endif
unsigned char VoltTable[] = {\n """

str2=""" 0 };\n"""

line = input_file.read().split('\r\n')
line = ','.join(line)

output_file.write(str1)
output_file.write(line)
output_file.write(str2)

input_file.close()
output_file.close()

Output

#ifdef EMBED
code //Needs to be placed in code memory for 2051
#endif
unsigned char VoltTable[] = {
3,6,9,12,15,18,21,23,26,29,32,34,37,40,42,45,47,50,52,55,57,59,62,64,
66,68,71,73,75,77,79,81,83,86,88,90,91,93,95,97,99,101,103,105,106,
108,110,112,113,115,117,118,120,121,123,125,126,128,129,131,132,
133,135,136,138,139,140,142,143,144,146,147,148,149,151,152,153,
154,155,157,158,159,160,161,162,163,164,165,166,167,168,169,170,
171,172,173,174,175,176,177,178,179,180,181,181,182,183,184,185,
185,186,187,188,189,189,190,191,192,192,193,194,194,195,196,196,
197,198,198,199,200,200,201,201,202,203,203,204,204,205,205,206,
206,207,208,208,209,209,210,210,211,211,212,212,212,213,213,214,
214,215,215,216,216,216,217,217,218,218,218,219,219,220,220,220,
221,221,221,222,222,222,223,223,223,224,224,224,225,225,225,226,
226,226,226,227,227,227,228,228,228,228,229,229,229,229,230,230,
230,230,231,231,231,231,232,232,232,232,233,233,233,233,233,234,
234,234,234,234,235,235,235,235,235,235,236,236,236,236,236,236,
237,237,237,237,237,237,238,238,238,238,238,238,238,239,239,239,
239,239, 0 };

Wednesday, August 23, 2006

itoa ( C )


void itoa( int n, char s[] )
{
int i, sign;
if ( ( sign = n ) < 0 )
n = -n;
i = 0;
do {
s[ i++ ] = n % 10 + '0';
} while ( n /= 10 ) > 0 );
if ( sign < 0 )
s[ i++ ] = '-';
s[ i ] = '\0';
reverse( s );
}

// P64, B. Kernighan, D. Ritchie, THE C PROGRAMMING LANGUAGE 2nd edition, Prentice Hall

reverse.c