Integer to string function doesn't account for 0

Posted on 2006-04-11
Last Modified: 2010-08-05
I've been using this function to convert integers into wide character strings, but I realized the function fails if the integer to be converted is 0.  This happens because the for loop breaks if it finds that val = 0.  

What are some workarounds to this problem?  

wchar_t* itowcs(int val, int base)
      static wchar_t buf[32] = {0};
      int i = 30;
      for(; val && i ; --i, val /= base) {
            buf[i] = L"0123456789abcdef"[val % base];
      return &buf[i+1];
Question by:chsalvia
    LVL 84

    Accepted Solution

     for(; (buf[i] = L"0123456789abcdef"[val % base]) && (val/=base) && --i ; ) {

      return &buf[i];
    LVL 16

    Expert Comment

    Neat code ozo!
    LVL 12

    Expert Comment

    Why not using this function instead of re-inventing the wheel
    wchar_t * _itow( int value, wchar_t *string, int radix );
    wchar_t * itow( int value, wchar_t *string, int radix );

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
    The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now