Develop a way to represent 32 bit numbers as 8-character strings (including the null character, so 7 characters of data). You can use 0-9 and a-z. Code it on the board. Develop unit test cases to test your code.
Base 36 number system, Leftmost char is sign char, ‘0’ for positive, ‘1’ for negative, rightmost char is ‘\0’:
0 0000 0000
1 0000 0010
…
35 0000 00z0
36 0000 0100
char* foo(int num, char* str)
{
for(int i=0;i<7;i++)
str[i]='0';
str[7]='\0';
if(num<0)
{
str[0]='1';
num=-1*num;
}
int idx=6;
while(num)
{
str[idx--]=get_char(num);
num=num/36;
}
return str;
}
char get_char(int num)
{
int tmp=num%36;
if(tmp<10)
return tmp+'0';
else
return (tmp-10)+'a';
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment