How to convert integer to char without C library?

前端 未结 3 732
盖世英雄少女心
盖世英雄少女心 2021-01-28 09:31

In a c programming exercise I am asked to convert an int to char without using the C library.

Any idea how to go about it?

edit: what I mean by int is the built

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-28 09:46

    Cast it?

    char c = (char)i;
    

    Or maybe you meant this?

    char c = (char)('0' + i);
    

    I'm sure this isn't what you mean though... I'm guessing you want to create a string (char array)? If so, then you need to convert it one digit at a time starting with the least significant digit. You can do it recursively, in pseudo-code:

    function convertToString(i)
       if i < 10
           return convertDigitToChar(i)
       else
           return convertDigitToString(i / 10) concat convertDigitToChar(i % 10)
    

    Here / is integer division and % is integer modulo. You also need to handle negative numbers. This can be done by checking first if you have a negative number, calling the function on the aboslute value and adding the minus sign if necessary.

    In C for performance you would probably implement this with a loop instead of using recursion, and by directly modifying the contents of a character array instead of concatenating strings.

提交回复
热议问题