开发者

Convert an integer to a string

I am trying to learn assem开发者_Python百科bler and want to write a function to convert a number to a string. The signature of the function I want to write would looks like this in a C-like fashion:

int numToStr(long int num, unsigned int bufLen, char* buf)

The function should return the number of bytes that were used if conversion was successful, and 0 otherwise.

My current approach is a simple algorithm. In all cases, if the buffer is full, return 0.

  1. Check if the number is negative. If it is, write a - char into buf[0] and increment the current place in the buffer
  2. Repeatedly divide by 10 and store the remainders in the buffer, until the division yields 0.
  3. Reverse the number in the buffer.

Is this the best way to do this conversion?


This is pretty much how every single implementation of itoa that I've seen works.

One thing that you don't mention but do want to take care of is bounds checking (i.e. making sure you don't write past bufLen).

With regards to the sign: once you've written the -, you need to negate the value. Also, the - needs to be excluded from the final reversal; an alternative is to remember the sign at the start but only write it at the end (just before the reversal).

One final corner case is to make sure that zero gets written out correctly, i.e. as 0 and not as an empty string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜