-
September 10th, 2009, 07:33 PM
#1
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
-
September 10th, 2009, 08:52 PM
#2
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.
-
September 10th, 2009, 08:57 PM
#3
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
-
September 10th, 2009, 09:23 PM
#4
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().
-
September 10th, 2009, 09:31 PM
#5
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|