ch3-utoa (Unsigned to string)

Chapter_3     Exercise_3-4 Exercise_3-5







Note:  utoa() is a simplified version of itoa() from Exercise_3-4. We will use utoa() for the Index_program in Chapter_5, Sec. 5.11. See also atou in Chapter_2, Sec. 2.7.




utoa.c         download


#include <stdio.h> // for printf(), scanf()

#define SIZE 100 // array size (max no of digits)

// reverse s, knowing its length:
void reverse(char s[], int len);
int utoa (unsigned , char []); // unsigned to string of chars

int main()
{
char digits[SIZE];
unsigned n;

printf ("Give an unsigned integer: ");
scanf ("%u", &n);

utoa(n, digits);

printf ("utoa(%u) = %s\n", n, digits);

return 0;
}
// reverse s, knowing its length:
void reverse(char s[], int len)
{
char temp;
int start = 0, end = len-1; // last position before '\0'

while (start < end)
{
temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
}
// get the digits of n into s[] (convert n to a string of characters),
// return the length of s[] (no of digits):
int utoa (unsigned n, char s[])
{
int len = 0; // length of s[]

do
{ // get the digits in reverse order:
s[len++] = (n % 10) + '0'; // get next (last read) digit
} while (n /= 10); // while ((n /= 10) > 0); // delete last digit

s[len] = '\0'; // end the string

reverse(s, len);

return len;
}
/*
gcc utoa.c -o utoa
./utoa
Give an unsigned integer: 0
utoa(0) = 0

./utoa
Give an unsigned integer: -0
utoa(0) = 0

./utoa
Give an unsigned integer: +0
utoa(0) = 0

./utoa
Give an unsigned integer: 1
utoa(1) = 1

./utoa
Give an unsigned integer: +123
utoa(123) = 123

./utoa
Give an unsigned integer: -1 (underflow - scanf() makes the conversion)
utoa(4294967295) = 4294967295 // UINT_MAX (limits.h)

./utoa
Give an unsigned integer: -2
utoa(4294967294) = 4294967294 // UINT_MAX-1 (modulo 2 arithmetic)

./utoa
Give an unsigned integer: 4294967295 // UINT_MAX
utoa(4294967295) = 4294967295

./utoa
Give an unsigned integer: 4294967296 // UINT_MAX + 1 (overflow)
utoa(0) = 0 // (modulo 2 arithmetic - scanf() makes the conversion)

./utoa
Give an unsigned integer: 4294967297 // UINT_MAX + 2
utoa(1) = 1 // (modulo 2 arithmetic)
*/









Chapter_3     Exercise_3-4 BACK_TO_TOP Exercise_3-5



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo