Thursday, February 18, 2010

Challenges solution : MyPrint()

Here is my solution for MyPrint().

#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
void print_int_hex(int val,int alg)
{
int i;
if (val==0)
{
_putch('0');
}
else
{
if (val/alg)
{
i = val % alg;
print_int_hex(val/alg,alg);
}
else
i = val % alg;
if (i>9)
{
i=i-10+'a';
_putch(i);
}
else
_putch(i?i+48:48);
}
}

void print_float(double val)
{
int temp = val *100;

if (val==0)
{
_putch('0');
}
else
{
print_int_hex(temp/100,10);
_putch('.');
print_int_hex(temp%100,10);
}
}

void MyPrint(char* pString,...)
{
int i=0;
int ch;
const char* str;
double f;

va_list args;
va_start(args, pString);
while (pString[i])
{
if (pString[i]=='%')
{
i++;
switch(pString[i])
{
case 'c':
ch = va_arg(args, int);
_putch(ch);
break;
case 's':
str = va_arg(args, const char*);
_cputs(str);
break;
case 'd':
ch = va_arg(args,int);
if (ch<0)
{
_putch('-');
ch=ch*(-1);
}
print_int_hex(ch,10);
break;
case 'x':
case 'X':
ch = va_arg(args, int);
print_int_hex(ch,16);
break;
case 'f':
f = va_arg(args, double);
print_float(f);
break;
}
i++;
}
_putch(pString[i]);
i++;
}
va_end(args);
}

int main()
{
MyPrint("int %d, char %c, string %s, hex %x, float %f", -102, 'A', "hello", 31, 12.34567);
return 0;
}

Result as:
int -102, char A, string hello, hex 1f, float 12.34
For float, I thought might be have better solution.

Wednesday, February 3, 2010

Optimizing bio_display()

Here is the source code:
void bio_display(const char *str, int row, int col, int len){
bio_move(row, col);
if(len <= 0){
bio_putstr(str);
}
else{
int i;
for(i=0; i< len && str[i];i++){
bio_putch(str[i]);
}
for(;i< len;i++){
bio_putch(' ');
}
}
}
To optimize it, I got this solution :
void bio_display(const char *str, int row, int col, int len) {
bio_move(row, col);
if( len <= 0)
bio_putstr(str);
else {
for(;len>0; len--) bio_putch(*str ? *str++ : ' ' );
}
}
From the same logic, it also can be shortened as:
void bio_display(const char *str, int row, int col, int len) {
for((bio_move(row, col), (len <= 0)?bio_putstr(str):0); len>0; len--)
bio_putch(*str ? *str++ : ' ' );
}
I tried to use bio_putstr() instead of bio_putch() which Farad mentioned in the class, but considered the length of the string I insisted to use bio_putch().