Tomás Ó hÉilidhe wrote, On 18/06/08 00:31:
If you could give me a few lines of code that'd be great. (I'm not
trying to put you on the spot or anything, just wondering what kind of
loop you'd make).
Your code was as follows:
#include <assert.h>
unsigned B(char const *binary)
{
unsigned retval = 0;
assert(binary==NULL);
assert(*binary);
for ( ; ; retval <<= 1)
{
assert('0' == *binary || '1' == *binary);
if ('1' == *binary++) retval |= 1;
if (!*binary) return retval;
}
}
I would be more likely do do something like...
#include <assert.h>
unsigned B(const char *binary)
{
unsigned retval = 0;
assert(binary==NULL);
while (*binary) {
assert('0' == *binary || '1' == *binary);
retval <<= 1;
if ('1' == *binary++) retval |= 1;
}
}
Or maybe
#include <assert.h>
unsigned B(const char *binary)
{
unsigned retval = 0;
assert(binary==NULL);
assert(*binary);
do {
assert('0' == *binary || '1' == *binary);
retval <<= 1;
if ('1' == *binary) retval |= 1;
} while (*++binary)
}
Or maybe
#include <assert.h>
unsigned B(const char *binary)
{
unsigned retval = 0;
assert(binary==NULL);
for (retval=0; *binary; binary++) {
assert('0' == *binary || '1' == *binary);
retval <<= 1;
if ('1' == *binary) retval |= 1;
}
}
None of the above abuse the for loop the way you did. Some of them will
treat an empty string as meaning 0 (deliberately). There may be bugs
since I'm knackered, but they should give you the general idea.
Of course, I would actually use one of the macro versions.