CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: A Question

  1. #1
    Join Date
    Aug 2009
    Location
    Egypt
    Posts
    8

    A Question

    I have the following code which converts to from base-10 to base-2 numbers:

    Code:
    static char binary[50];
    char* ptr = &binary[sizeof(binary)-1];
    
    *ptr = '\0';
    while(n != 0)
    {
    	*--ptr = "0123456789abcdef"[n % 2];
    	n /= 2;
    }
    I understand everything except

    Code:
     "0123456789abcdef"[n % 2];
    I've got this line from someone's code

    As far as i understand this is supposed to decrease the pointer and dereference it to fill the next (or previous since we work in binary) element but what does the "0123456789absded" do?

    I've tried to replace it with other values but apparently it have to be hexadecimal.

    Thanks

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: A Question

    The only relevant part of that is "01", since it's impossible for n%2 to be anything other than 0 or 1. It's simply selecting the proper character to add to the string.

    As for why the other characters are there? Presumably, to make it easier to change the function so that it converts to a different base.
    Last edited by Lindley; September 10th, 2009 at 08:55 PM.

  3. #3
    Join Date
    Aug 2009
    Location
    Egypt
    Posts
    8

    Re: A Question

    Thank you Lindley,

    I won't be using it since it's not safe, But i still curious to know what does these characters do in this case?

    Regards

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: A Question

    It's just a literal string. You can think of it as an array containing those characters if you want.

    And I retract my comment about safety----50 characters should be enough to handle the binary representation of any 32-bit int, obviously. 64-bit ints would be an issue.

    The simplest way to do this conversion, though, is to use std::bitset<N>::to_string().

  5. #5
    Join Date
    Aug 2009
    Location
    Egypt
    Posts
    8

    Re: A Question

    Thanks Lindley,
    I would use the method you've provided next time I was just training myself to work with those types.

    Regards

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured