By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,159 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

integers to binary

P: n/a
I've been trying to write a program that converts an entered number into its
binary representation using three different techniques - bit shifting, mod
2, and itoa..

However, I'm getting 'snow blind', and can't get the non-ISO itoa to work as
I'd like. The snow blindness makes me think it's me, and not the function!

The idea of the program was to be able to change #define I_TYPE char to any
scalar type, re-compile, and then play. Limited success so far though, and
I'm sure the code could be 'better'.

Any constructive comments welcome.

#include <stdio.h >
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define I_TYPE char

#define K sizeof(I_TYPE) * CHAR_BIT
// Forward decs.
//
char * binary1(I_TYPE n);
char * binary2(I_TYPE n);
char * binary3(I_TYPE n);
char * strrev (char * str);

int main(void)
{
char buffer[100];

puts("Enter numbers to convert to binary, or hit enter to quit");

while(strlen(fgets(&buffer[0], sizeof(buffer), stdin)) > 1)
{
I_TYPE l = (I_TYPE)strtol(&buffer[0], NULL, 10);

puts(binary1(l));

puts(binary2(l));

puts(binary3(l));
}

return 0;
}

char * binary1(I_TYPE n)
{
// Loop counter.
//
int i = 0;

// Bit-mask.
//
unsigned long int j = 1;

// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];

buffer[sizeof(buffer) - 1] = '\0';

for(i = 0; i < K; i++)
{
buffer[i] = (n & j) == j ? '1' : '0';

j = j << 1;
}

return strrev(buffer);
}

char * binary2(I_TYPE n)
{
int i;

// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];

buffer[sizeof(buffer) - 1] = '\0';

for(i = K - 1; i >= 0; n /= (unsigned long int)2)
{
buffer[i--] = n % 2 == 0 ? '0' : '1';
}

return buffer;
}

char * binary3(I_TYPE n)
{
// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];

buffer[sizeof(buffer) - 1] = '\0';

// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);

return buffer;
}

char * strrev(char * s)
{
char * p1;
char * p2;

if (!s || !*s)
{
return s;
}

else

{
for(p1 = s, p2 = s + strlen(s) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
}

return s;
}
Dec 13 '05 #1
Share this Question
Share on Google+
40 Replies


P: n/a
rayw wrote:
However, I'm getting 'snow blind',
and can't get the non-ISO itoa to work as I'd like.
The snow blindness makes me think it's me, and not the function! // itoa() not a standard ISO function.
//
itoa(n, buffer, 2);


This is the wrong newsgroup to ask about your itoa.
Doesn't your library have any documentation?

--
pete
Dec 13 '05 #2

P: n/a

"pete" <pf*****@mindspring.com> wrote in message
news:43**********@mindspring.com...
rayw wrote:
However, I'm getting 'snow blind',
and can't get the non-ISO itoa to work as I'd like.
The snow blindness makes me think it's me, and not the function!

// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);


This is the wrong newsgroup to ask about your itoa.
Doesn't your library have any documentation?


Yes, it does, but I was hoping to get some theory here as to what it's
doing: I don't have the source.

For example, if you run the program 'as posted' and enter 255 for the value,
the output is:

[compiler 1: gcc]
255
11111111
11111111
11111111111111111111111111111111

[compiler 2: msvc]
255
11111111
11111111
11111111111111111111111111112111

If you enter something like 128, you get this

[compiler 1: gcc]
128
10000000
10000000
11111111111111111111111110000000

[compiler 2: msvc]
128
10000000
10000000
11111111111111111111111110001000

but for 127, you get this

[compiler 1: gcc]
127
01111111
01111111
1111111

[compiler 2: msvc]
127
01111111
01111111
1111111

So, I *think* there's 'weird stuff going on' - and that's about as
descriptive as I can get.

btw, on trying to debug the above, I noticed that msvc's itoa overwrites the
buffer, e.g., for 255 it returns

11111111111111111111111111111111

<--- 32 --->

So, I altered my code in binary3 to set the buffer larger:

static char buffer[sizeof(unsigned long int) * CHAR_BIT + 1];

That's cured most of the weirdness, but I'd like to understand what's going
on when you use an initial value like 128 - like it's using signed long ints
internally or something?

[from *both* msvc and gcc now]
128
10000000
10000000
11111111111111111111111110000000

Any clues as to what itoa might be doing?
Dec 13 '05 #3

P: n/a
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote:
I've been trying to write a program that converts an entered number into its
binary representation using three different techniques - bit shifting, mod
2, and itoa..

However, I'm getting 'snow blind', and can't get the non-ISO itoa to work as
I'd like. The snow blindness makes me think it's me, and not the function!
See below for comments about itoa().
The idea of the program was to be able to change #define I_TYPE char to any
scalar type, re-compile, and then play. Limited success so far though, and
I'm sure the code could be 'better'.
Why, yes. Yes it can.
Any constructive comments welcome.
Alright. I hope I haven't missed anything.
#include <stdio.h >
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define I_TYPE char
Alright. I'll play. No comment, given that I_TYPE can change.
#define K sizeof(I_TYPE) * CHAR_BIT
'K' is not a very verbose identifier. I wouldn't know what it's for by
looking at it.

Also, I_TYPE could contain padding bits and a sign bit. Perhaps you should
do something with xxx_MAX instead? I'll let you work on it.
char * binary1(I_TYPE n);
char * binary2(I_TYPE n);
char * binary3(I_TYPE n);
char * strrev (char * str); int main(void)
{
char buffer[100];

puts("Enter numbers to convert to binary, or hit enter to quit");

while(strlen(fgets(&buffer[0], sizeof(buffer), stdin)) > 1)
Bang!

What if fgets() fails? It's going to return NULL when it does. Don't you
want to know?

Oh, and strlen(NULL) is undefined.
{
I_TYPE l = (I_TYPE)strtol(&buffer[0], NULL, 10);
As I said before, l is a char at the moment, though it could be anything.
strtol's return type doesn't fit in there unless you're very very lucky,
because strtol() always returns a long.

strtol() also has this neat error reporting thing. You should use it.

Here's how to 'fix' this thing:
- l should be a long. Remove the cast.
- Check for errors (is l negative? Does errno equal ERANGE and is l
LONG_MIN or LONG_MAX?)
- Check if the value of l fits in an I_TYPE.
- Assign l to an I_TYPE.
puts(binary1(l));
puts(binary2(l));
puts(binary3(l));
}
return 0;
}
You use a lot of blank lines that serve no purpose I can detect.
char * binary1(I_TYPE n)
{
// Loop counter.
//
C++ type comments have been included in the C standard in C99 (and has
been available as a compiler extension in many compilers for years
before it was published). However, C99 is not quite the leading standard
just yet. Also, these comments can cause painful things on Usenet, though
I'll admit this comment isn't quite long enough for that. Perhaps after
being quoted in follow-ups a few dozen times.
int i = 0;
Why not remove the comment and call it loop_counter?
// Bit-mask.
//
unsigned long int j = 1;
Why not remove the comment and call it bit_mask?

More comments on 'j' below.
// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];
I'm a bit confused about this. Did you just declare buffer with static
storage duration because it's been defined in main() already? Because you
really don't have to. Read your C book up to and including the topic about
'scope'.
buffer[sizeof(buffer) - 1] = '\0';
for(i = 0; i < K; i++)
{
buffer[i] = (n & j) == j ? '1' : '0';
This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}
j = j << 1;
I can imagine what would happen if I_TYPE is wider than an unsigned long
int. Perhaps you should make j an I_TYPE? That would make sense, wouldn't
it?
}
return strrev(buffer);
You know how long the string's going to be in advance. Why not just fill
it the other way around (from K to 0 instead of from 0 to K)?

Though, okay, it's another method of converting it. I'll play.
} char * binary2(I_TYPE n)
{
int i;

// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];
Again with this mysterious static, and the even more mysterious comment...
buffer[sizeof(buffer) - 1] = '\0';

for(i = K - 1; i >= 0; n /= (unsigned long int)2)
How about:
for (i = K-1; i >= 0; i--)

That keeps the loop nice and central. You'll have to change some other
things too to make the loop work again, but I'll leave those to you.
{
buffer[i--] = n % 2 == 0 ? '0' : '1';
See the last comment about awful expressions. Conditional expressions
should generally be avoided (IMHO).
}
return buffer;
} char * binary3(I_TYPE n)
{
// 'static' essential - buffer is a local variable!!
//
static char buffer[K + 1];
Repeat.
buffer[sizeof(buffer) - 1] = '\0';

// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);
Indeed it isn't. I don't have it.

Though according to http://www.mkssoftware.com/docs/man3/itoa.3.asp this
should work, unless I've gone blind.

What does it make of it? What do you /expect/ it to make of it?
return buffer;
} char * strrev(char * s)
{
char * p1;
char * p2;

if (!s || !*s)
{
return s;
}
else
{
for(p1 = s, p2 = s + strlen(s) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
Though the swapping works, there's nothing wrong with just using a
temporary. I don't really know of a really good reason to do it this way.
}
}
return s;
}


--
Pieter Droogendijk <pieter at binky dot org dot uk>
PGP/1E92DBBC [ Make way for the Emperor's Finest. ] binky.org.uk

Dec 13 '05 #4

P: n/a

"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
news:pa****************************@binkySPAM.orgF OR.ukME...
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote:
I've been trying to write a program that converts an entered number into
its
binary representation using three different techniques - bit shifting,
mod
2, and itoa..

However, I'm getting 'snow blind', and can't get the non-ISO itoa to work
as
I'd like. The snow blindness makes me think it's me, and not the
function!
See below for comments about itoa().
The idea of the program was to be able to change #define I_TYPE char to
any
scalar type, re-compile, and then play. Limited success so far though,
and
I'm sure the code could be 'better'.


Why, yes. Yes it can.


<snip>
I'm a bit confused about this. Did you just declare buffer with static
storage duration because it's been defined in main() already? Because you
really don't have to. Read your C book up to and including the topic about
'scope'.


Each binary?'()s local buffer is declared static as each of them returns
&buffer[0] to the caller - so, nothing to do with scope, just don't want to
return a frame variable.
buffer[sizeof(buffer) - 1] = '\0';
for(i = 0; i < K; i++)
{
buffer[i] = (n & j) == j ? '1' : '0';


This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines of code, and
duplicates the assignment etc, I think it's more prone to errors later -
like if someone changes it.

<snip>
// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);


Indeed it isn't. I don't have it.

Though according to http://www.mkssoftware.com/docs/man3/itoa.3.asp this
should work, unless I've gone blind.


Thanks for the ref and the comments.
Dec 13 '05 #5

P: n/a
On Tue, 13 Dec 2005 13:28:09 +0000, rayw wrote:
"pete" <pf*****@mindspring.com> wrote in message [...]
This is the wrong newsgroup to ask about your itoa.
Doesn't your library have any documentation?


Yes, it does, but I was hoping to get some theory here as to what it's
doing: I don't have the source.


You haven't described the prototype, but likely the first parameter is an
int, to which your char would be converted, and which would require an
appropriately sized buffer...
So, I altered my code in binary3 to set the buffer larger:

static char buffer[sizeof(unsigned long int) * CHAR_BIT + 1];

That's cured most of the weirdness


....as you discovered.

Reading the documentation carefully will probably help explain any other
unexpected behaviour.

One (likely unrelated) error in your code is the space between the end
of "stdio.h" and the closing ">" in the #include directive.

Make sure you're compiling in standards mode with warnings enabled.

[...]
--
http://members.dodo.com.au/~netocrat
Dec 13 '05 #6

P: n/a
rayw wrote:

I've been trying to write a program that converts an entered
number into its binary representation using three different
techniques - bit shifting, mod 2, and itoa..

However, I'm getting 'snow blind', and can't get the non-ISO
itoa to work as I'd like. The snow blindness makes me think
it's me, and not the function!

The idea of the program was to be able to change #define I_TYPE
char to any scalar type, re-compile, and then play. Limited
success so far though, and I'm sure the code could be 'better'.

Any constructive comments welcome.


.... snip long winded code etc. ...

The following, which includes a test routine enabled by defining
TESTING at compile time, will convert any unsigned integral types
to a string on the output file. To handle signed values just
output a - sign and then use putword for the negation. Watch out
for maximum values with 2's complement.

#include <stdio.h>

int putword(unsigned long w, FILE *f)
{
if (w > 9)
if (0 > putword(w / 10, f)) return EOF;
return putc((w % 10) + '0', f);
} /* putword */

/* --------------- */

#ifdef TESTING

#include <stdlib.h>

int main(void)
{
int i;

for (i = 0; i < 10; i++) {
putword(i, stdout);
putc(' ', stdout);
putword(rand(), stdout);
putc('\n', stdout);
}
return 0;
} /* main */
#endif

--
Read about the Sony stealthware that is a security leak, phones
home, and is generally illegal in most parts of the world. Also
the apparent connivance of the various security software firms.
http://www.schneier.com/blog/archive...drm_rootk.html
Dec 13 '05 #7

P: n/a
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:

"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
news:pa****************************@binkySPAM.org FOR.ukME...
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote:
buffer[i] = (n & j) == j ? '1' : '0';


This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines of code, and
duplicates the assignment etc, I think it's more prone to errors later -
like if someone changes it.


IME readable code is considerably easier to maintain than unreadable
code. Write for readability first. Consider clever tricks only if
trying to obfuscate code.

if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 13 '05 #8

P: n/a

"Netocrat" <ne******@dodo.com.au> wrote in message
news:pa****************************@dodo.com.au...
On Tue, 13 Dec 2005 13:28:09 +0000, rayw wrote:
<snip>
One (likely unrelated) error in your code is the space between the end
of "stdio.h" and the closing ">" in the #include directive.


That's an error? I thought the preprocessor ignored such things?
Dec 13 '05 #9

P: n/a
On Tue, 13 Dec 2005 19:50:47 +0000, rayw wrote:
"Netocrat" <ne******@dodo.com.au> wrote in message
news:pa****************************@dodo.com.au...

[...]
One (likely unrelated) error in your code is the space between the end
of "stdio.h" and the closing ">" in the #include directive.


That's an error? I thought the preprocessor ignored such things?


"<" and ">" are delimiters. Everything between them is interpreted as the
header name, including the space. The same applies when double quotes are
used as the delimiters. (a newline character within the header name
delimiters is invalid though)

--
http://members.dodo.com.au/~netocrat
Dec 13 '05 #10

P: n/a
rayw wrote:

[n is a char]
itoa(n, buffer, 2);
This is the wrong newsgroup to ask about your itoa.
Doesn't your library have any documentation?


Yes, it does, but I was hoping to get some theory here as to
what it's doing: I don't have the source.


The relevant line in the documentation is:

char *itoa(int value, char *string, int radix);

and in particular, that itoa is expecting 'value' to be an int.
For example, if you run the program 'as posted' and enter
255 for the value, the output is:

[compiler 1: gcc]
11111111111111111111111111111111

[compiler 2: msvc]
11111111111111111111111111112111

If you enter something like 128, you get this
[compiler 1: gcc]
11111111111111111111111110000000

[compiler 2: msvc]
11111111111111111111111110001000

but for 127, you get this
[compiler 1: gcc]
1111111
[compiler 2: msvc]
1111111

So, I *think* there's 'weird stuff going on' - and that's about as
descriptive as I can get.


128 and 255 are not valid values for 'char'. char values are in
the range -128 to 127[*]. You cause your program to be
unreliable when you assign out-of-range values to chars.

Here is a fuller description of what is happening, please bear
in mind that this behaviour is peculiar to some systems only
(eg. IA32), and doesn't hold in the general case.
When you assign the int 128 to your char, the compiler tries
to squish 0x00000080 into eight bits, which results in 0x80,
which is the value -128 when used as the bit-pattern for a char.
So the itoa function receives the value of -128. To find out
what itoa does when you give it a negative number you will
have to read your compiler's documentation (mine has an
itoa function but it only specifies negative number behaviour
when radix is 10).

Based on your output I'd say that it is printing the bit pattern
of the negative number, and in binary the int -128 is indeed
11111111111111111111111110000000 .
Since your buffer is less than 33 bytes, anything could
happen really, you're lucky that GCC even managed to
not screw up the end of the buffer, although MSVC clearly
did (as it is entitled to, of course).

A similar explanation applies to the 255 case (which gets
the value -1, and has bit-pattern of all 1s).
[*] In general they can be in a variety of ranges, and the actual
range is specified by CHAR_MIN and CHAR_MAX in limits.h .
But it's clear from your post that your system has this range.

Dec 13 '05 #11

P: n/a
rayw wrote:
I've been trying to write a program that converts an entered number
into its binary representation using three different techniques - bit
shifting, mod 2, and itoa..
See my other post explaining about your use of itoa.
I have some other comments on y our code which
hopefully you will find helpful.
#include <stdio.h >
No space !
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#define I_TYPE char
Most importantly, you should use an unsigned type
for anything that you are planning to do bit-shifts on,
because signed types cause trouble as you have seen.

It is usually better to use a typedef:
typedef unsigned int I_TYPE;

Also you will find it easier to start off with an int, and
then work down to a char (everything in C is designed
to work best with ints).

#define K sizeof(I_TYPE) * CHAR_BIT

// Forward decs.
//
char * binary1(I_TYPE n);
char * binary2(I_TYPE n);
char * binary3(I_TYPE n);
char * strrev (char * str);
Strictly speaking you should not call your functions anything
starting with str followed by a lower case letter, because
it might clash with future updates to string.h .
int main(void)
{
char buffer[100];
puts("Enter numbers to convert to binary, or hit enter to quit");

while(strlen(fgets(&buffer[0], sizeof(buffer), stdin)) > 1)
fgets() returns NULL on failure.. you'll need to re-arrange this test.
Also you can just write 'buffer' everywhere you have &buffer[0],
it means exactly the same thing in most contexts.
{
I_TYPE l = (I_TYPE)strtol(&buffer[0], NULL, 10);
Don't use this cast. It doesn't gain you anything.
puts(binary1(l));
puts(binary2(l));
puts(binary3(l));
}

return 0;
}

char * binary1(I_TYPE n)
{
int i = 0;
unsigned long int j = 1;
static char buffer[K + 1];

buffer[sizeof(buffer) - 1] = '\0';
for(i = 0; i < K; i++)
{
buffer[i] = (n & j) == j ? '1' : '0';
j = j << 1;
This will give you unexpected results if n is negative -- which is
why I_TYPE should be unsigned.

Also it's possible to be more concise (and clearer IMHO):

buffer[i] = (n & j) ? '1' : '0';
j <<= 1;
}

return strrev(buffer);
}

char * binary2(I_TYPE n)
{
int i;
static char buffer[K + 1];
buffer[sizeof(buffer) - 1] = '\0';

for(i = K - 1; i >= 0; n /= (unsigned long int)2)
You can write 2UL instead of the cast notation.
buffer[i--] = n % 2 == 0 ? '0' : '1';
return buffer;
}

char * strrev(char * s)
{
char * p1;
char * p2;

if (!s || !*s)
return s;
else
for(p1 = s, p2 = s + strlen(s) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
Please don't do that: it just confuses people who haven't
seen it before. Far clearer is:

char tmp = *p1;
*p1 = *p2;
*p2 = tmp;

return s;
}


Dec 13 '05 #12

P: n/a
Mark McIntyre <ma**********@spamcop.net> writes:
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:
buffer[i] = (n & j) == j ? '1' : '0';


if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


buffer[i] = ((n & j) == j) + '0';

Style issue.

/Niklas Norrthon
Dec 14 '05 #13

P: n/a

"Old Wolf" <ol*****@inspire.net.nz> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
rayw wrote:

[n is a char]
itoa(n, buffer, 2);

This is the wrong newsgroup to ask about your itoa.
Doesn't your library have any documentation?


Yes, it does, but I was hoping to get some theory here as to
what it's doing: I don't have the source.


The relevant line in the documentation is:

char *itoa(int value, char *string, int radix);

and in particular, that itoa is expecting 'value' to be an int.
For example, if you run the program 'as posted' and enter
255 for the value, the output is:

[compiler 1: gcc]
11111111111111111111111111111111

[compiler 2: msvc]
11111111111111111111111111112111

If you enter something like 128, you get this
[compiler 1: gcc]
11111111111111111111111110000000

[compiler 2: msvc]
11111111111111111111111110001000

but for 127, you get this
[compiler 1: gcc]
1111111
[compiler 2: msvc]
1111111

So, I *think* there's 'weird stuff going on' - and that's about as
descriptive as I can get.


128 and 255 are not valid values for 'char'. char values are in
the range -128 to 127[*]. You cause your program to be
unreliable when you assign out-of-range values to chars.

Here is a fuller description of what is happening, please bear
in mind that this behaviour is peculiar to some systems only
(eg. IA32), and doesn't hold in the general case.
When you assign the int 128 to your char, the compiler tries
to squish 0x00000080 into eight bits, which results in 0x80,
which is the value -128 when used as the bit-pattern for a char.
So the itoa function receives the value of -128. To find out
what itoa does when you give it a negative number you will
have to read your compiler's documentation (mine has an
itoa function but it only specifies negative number behaviour
when radix is 10).

Based on your output I'd say that it is printing the bit pattern
of the negative number, and in binary the int -128 is indeed
11111111111111111111111110000000 .
Since your buffer is less than 33 bytes, anything could
happen really, you're lucky that GCC even managed to
not screw up the end of the buffer, although MSVC clearly
did (as it is entitled to, of course).

A similar explanation applies to the 255 case (which gets
the value -1, and has bit-pattern of all 1s).

[*] In general they can be in a variety of ranges, and the actual
range is specified by CHAR_MIN and CHAR_MAX in limits.h .
But it's clear from your post that your system has this range.


Many thanks - clear now!
Dec 14 '05 #14

P: n/a

"Old Wolf" <ol*****@inspire.net.nz> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
rayw wrote:
I've been trying to write a program that converts an entered number
into its binary representation using three different techniques - bit
shifting, mod 2, and itoa..


See my other post explaining about your use of itoa.
I have some other comments on y our code which
hopefully you will find helpful.
#include <stdio.h >


No space !
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#define I_TYPE char


Most importantly, you should use an unsigned type
for anything that you are planning to do bit-shifts on,
because signed types cause trouble as you have seen.

It is usually better to use a typedef:
typedef unsigned int I_TYPE;

Also you will find it easier to start off with an int, and
then work down to a char (everything in C is designed
to work best with ints).

#define K sizeof(I_TYPE) * CHAR_BIT

// Forward decs.
//
char * binary1(I_TYPE n);
char * binary2(I_TYPE n);
char * binary3(I_TYPE n);
char * strrev (char * str);


Strictly speaking you should not call your functions anything
starting with str followed by a lower case letter, because
it might clash with future updates to string.h .
int main(void)
{
char buffer[100];
puts("Enter numbers to convert to binary, or hit enter to quit");

while(strlen(fgets(&buffer[0], sizeof(buffer), stdin)) > 1)


fgets() returns NULL on failure.. you'll need to re-arrange this test.
Also you can just write 'buffer' everywhere you have &buffer[0],
it means exactly the same thing in most contexts.
{
I_TYPE l = (I_TYPE)strtol(&buffer[0], NULL, 10);


Don't use this cast. It doesn't gain you anything.
puts(binary1(l));
puts(binary2(l));
puts(binary3(l));
}

return 0;
}

char * binary1(I_TYPE n)
{
int i = 0;
unsigned long int j = 1;
static char buffer[K + 1];

buffer[sizeof(buffer) - 1] = '\0';
for(i = 0; i < K; i++)
{
buffer[i] = (n & j) == j ? '1' : '0';
j = j << 1;


This will give you unexpected results if n is negative -- which is
why I_TYPE should be unsigned.

Also it's possible to be more concise (and clearer IMHO):

buffer[i] = (n & j) ? '1' : '0';
j <<= 1;
}

return strrev(buffer);
}

char * binary2(I_TYPE n)
{
int i;
static char buffer[K + 1];
buffer[sizeof(buffer) - 1] = '\0';

for(i = K - 1; i >= 0; n /= (unsigned long int)2)


You can write 2UL instead of the cast notation.
buffer[i--] = n % 2 == 0 ? '0' : '1';
return buffer;
}

char * strrev(char * s)
{
char * p1;
char * p2;

if (!s || !*s)
return s;
else
for(p1 = s, p2 = s + strlen(s) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}


Please don't do that: it just confuses people who haven't
seen it before. Far clearer is:

char tmp = *p1;
*p1 = *p2;
*p2 = tmp;

return s;
}


Many thanks - v.useful comments
Dec 14 '05 #15

P: n/a
Niklas Norrthon wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:
buffer[i] = (n & j) == j ? '1' : '0';

if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


buffer[i] = ((n & j) == j) + '0';

Style issue.


Indeed it is a style issue. However, your contribution is too clever for
its own good. It's correct, but it's harder to read and harder to
understand. Remember that C code is written 10% for the compiler and 90%
for the maintenance programmer. Understanding this code requires some
extra connections to be made:
1. a Boolean expression has an integer value of 0 or 1
2. digits are sequential, ie. '0' + 1 == '1'
While any good C programmer knows these two facts, it takes time and
brain cycles to put it all together, which could be avoided by not being
so clever.

--
Simon.
Dec 14 '05 #16

P: n/a
Simon Biber wrote:

Niklas Norrthon wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:
buffer[i] = (n & j) == j ? '1' : '0';

if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


buffer[i] = ((n & j) == j) + '0';

Style issue.


Indeed it is a style issue. However,
your contribution is too clever for
its own good. It's correct, but it's harder to read and harder to
understand. Remember that C code is written
10% for the compiler and 90%
for the maintenance programmer. Understanding this code requires some
extra connections to be made:
1. a Boolean expression has an integer value of 0 or 1
2. digits are sequential, ie. '0' + 1 == '1'
While any good C programmer knows these two facts, it takes time and
brain cycles to put it all together,
which could be avoided by not being so clever.


I liked "rayw"'s original version:

buffer[i] = (n & j) == j ? '1' : '0';

That's just about as simple a use of the conditional operator,
as there can be.
Some people just don't like the conditional operator,
but I'm not one of them.

--
pete
Dec 14 '05 #17

P: n/a
Mark McIntyre <ma**********@spamcop.net> writes:
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:

"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
news:pa****************************@binkySPAM.org FOR.ukME...
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote:

buffer[i] = (n & j) == j ? '1' : '0';

This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines of code, and
duplicates the assignment etc, I think it's more prone to errors later -
like if someone changes it.


IME readable code is considerably easier to maintain than unreadable
code. Write for readability first. Consider clever tricks only if
trying to obfuscate code.

if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


The original single assignment is precisely the sort of situation
where using the ?: operator makes sense. If Mr. McIntyre says he
finds the if/else form with two assignments more readable, I'm expect
that's so, but his reaction isn't shared by everyone. IMO the
single assignment using ?: is both more readable and more clear
than using if/else and two assignments.
Dec 14 '05 #18

P: n/a
On Tue, 13 Dec 2005 15:42:49 +0000, rayw wrote:

"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
news:pa****************************@binkySPAM.orgF OR.ukME...
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote:

<snap>
I'm a bit confused about this. Did you just declare buffer with static
storage duration because it's been defined in main() already? Because you
really don't have to. Read your C book up to and including the topic about
'scope'.


Each binary?'()s local buffer is declared static as each of them returns
&buffer[0] to the caller - so, nothing to do with scope, just don't want to
return a frame variable.


Whoops.
Forget my comments about it. Erase them from Usenet. It was temporary
insanity. I was tired. It was the dog that done it.
buffer[i] = (n & j) == j ? '1' : '0';


This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines of code, and
duplicates the assignment etc, I think it's more prone to errors later -
like if someone changes it.


Sure it's six lines for what could be one assignment, but it's as clear
as it's going to get. That's what I aim for, Unless obfuscation is what I
want.

But each to their own, of course.
// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);


Indeed it isn't. I don't have it.

Though according to http://www.mkssoftware.com/docs/man3/itoa.3.asp this
should work, unless I've gone blind.


Thanks for the ref and the comments.


Google rules.

--
Pieter Droogendijk <pieter at binky dot org dot uk>
PGP/1E92DBBC [ Make way for the Emperor's Finest. ] binky.org.uk

Dec 14 '05 #19

P: n/a
On 14 Dec 2005 09:14:23 +0100, in comp.lang.c , Niklas Norrthon
<do********@invalid.net> wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
On Tue, 13 Dec 2005 15:42:49 -0000, in comp.lang.c , "rayw"
<ra*********@gmail.com> wrote:
> buffer[i] = (n & j) == j ? '1' : '0';


if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';


buffer[i] = ((n & j) == j) + '0';


cute, but less readable, IMHO. Better then the original tho.
Style issue.


Readability issue too.

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 14 '05 #20

P: n/a
On 14 Dec 2005 03:51:59 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(on the topic of the 'niceness' of)
buffer[i] = (n & j) == j ? '1' : '0';

The original single assignment is precisely the sort of situation
where using the ?: operator makes sense.


Perhaps, once suitably parenthesised so that future maintenance drones
can understand it easily and w/o recourse to a manual of operator
precedence.
And it'd be a bit different if it were

foobar = (banana(12,34,pip(),333, printf("hello"))&&z)==blabla(bl,pl,
ypr)?pfngetarraycnt(yaddayadda,4) : atoi(getstringfrom(ww));

which is technically also a single assignment.
If Mr. McIntyre says he
finds the if/else form with two assignments more readable, I'm expect
that's so, but his reaction isn't shared by everyone.
Of course. Some people /like/ obfuscated code :-)
IMO the
single assignment using ?: is both more readable and more clear
than using if/else and two assignments.


YMMV.

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 14 '05 #21

P: n/a
Pieter Droogendijk wrote:
On Tue, 13 Dec 2005 15:42:49 +0000, rayw wrote:
"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote:

.... snip ...

This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines
of code, and duplicates the assignment etc, I think it's more
prone to errors later - like if someone changes it.


Sure it's six lines for what could be one assignment, but it's
as clear as it's going to get. That's what I aim for, Unless
obfuscation is what I want.


How about:

if ((n & j) == j) buffer[i] = '1';
else buffer[i] = '0';

Just a matter of style. Fairly hard to misread.

More important is the meaning of "(n & j) == j", which expresses
the assertion that all bits set in j are set in n. Thus another
alternative could be:

buffer[i] = '0' + ((n & j) == j);

All this exposes some possible portability problems, dependent on
the types of n and j.

--
Read about the Sony stealthware that is a security leak, phones
home, and is generally illegal in most parts of the world. Also
the apparent connivance of the various security software firms.
http://www.schneier.com/blog/archive...drm_rootk.html
Dec 15 '05 #22

P: n/a
On Tue, 13 Dec 2005 19:06:40 +0000, Mark McIntyre
<ma**********@spamcop.net> wrote:
<snip>
IME readable code is considerably easier to maintain than unreadable
code. Write for readability first. Consider clever tricks only if
trying to obfuscate code.

if ( (n & j) == j )
buffer[i]='1';
else
buffer[i]='0';

<snip: rather than conditional aka 'ternary' expression>

Agree on the principle, disagree strongly on the result.

The conditional operator in C is not obfuscation when it matches the
operation you want to perform, and here that fact that we want to put
one or another digit value in the _same_ output location is important.

What about (slightly sanitized from code I've worked on):
if( (n & j) == j )
currentOutputPtr->outputControl.workingbuffer[1].byte[i] = '1';
else
currentOutputPtr->outputControl.workingbuffer[1].byte[i] = '0';

Or suppose it were octal:
if( ( inputField.workingvalue4 >> shiftthisdigit & 7) == 0 )
currentOutputPtr->outputControl.workingbuffer[1].byte[i] = '0';
else if( ( inputField.workingvalue4 >> shiftthisdigit & 7) == 1 )
currentOutputPtr->outputControl.workingbuffer[1].byte[i] = '1';
and so on up to 7

and during maintenance you need to change to use workingbuffer[3]
will you get it right -- or if not, easily see, or test, the error?

Do you consider some_long[and].complicated->expression += 1
to be obfuscated for some_long[and].complicated->expression
= some_long[and].complicated->expression + 1? AFAIK compound
assignments are unique to the C family among HLLs.

In fact, what I would consider obfuscated is the (n & j) == j part. In
the example upthread j is always one bit and to me the natural way of
expressing "the/any bit on" is (n & j) != 0 -- or in a boolean context
like this just (n & j), but that's a whole 'nother argument.
To me (n & j) == j implies that we are at least sometimes looking for
multiple bits, and then I find it at least as clear to deMorganize to
"no masked bits off" and write !(~n & j) .

DG(N?)D.

- David.Thompson1 at worldnet.att.net
Dec 19 '05 #23

P: n/a
On Mon, 19 Dec 2005 03:20:49 GMT, in comp.lang.c , Dave Thompson
<da*************@worldnet.att.net> wrote:
On Tue, 13 Dec 2005 19:06:40 +0000, Mark McIntyre
<ma**********@spamcop.net> wrote:
<snip>
IME readable code is considerably easier to maintain than unreadable
code. Write for readability first. Consider clever tricks only if
trying to obfuscate code.
Agree on the principle, disagree strongly on the result.


Thats fine - I was advocating readability rather than removal of the
ternary operator.
The conditional operator in C is not obfuscation when it matches the
operation you want to perform,


Cautiously agree, with caveat that examples the other way are easy to
find too.

(snip examples of where ternary would be considerably clearer)
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 19 '05 #24

P: n/a
In article <dn**********@news.ox.ac.uk> "rayw" <ra*********@gmail.com> writes:
"Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
news:pa****************************@binkySPAM.orgF OR.ukME...
On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote: ....
buffer[i] = (n & j) == j ? '1' : '0';


This expression could be nicer. How's this:

if ( (n & j) == j ) {
buffer[i] = '1';
}
else {
buffer[i] = '0';
}


I agree that to some it's more readable, but as it's more lines of code, and
duplicates the assignment etc, I think it's more prone to errors later -
like if someone changes it.


Why not just: buffer[i] = (n & j) == j;
?
// itoa() not a standard ISO function.
//
itoa(n, buffer, 2);


Indeed it isn't. I don't have it.

Though according to http://www.mkssoftware.com/docs/man3/itoa.3.asp this
should work, unless I've gone blind.


Thanks for the ref and the comments.


I think itoa expects an int and you pass it a (probably) signed char.
You ought to know how a signed char with a negative value is passed
in a position where an int is expected.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Dec 19 '05 #25

P: n/a
In article <Ir********@cwi.nl> "Dik T. Winter" <Di********@cwi.nl> writes:
In article <dn**********@news.ox.ac.uk> "rayw" <ra*********@gmail.com> writes:
> "Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME> wrote in message
> news:pa****************************@binkySPAM.orgF OR.ukME...
> > On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote: ... > >> buffer[i] = (n & j) == j ? '1' : '0';
> >
> > This expression could be nicer. How's this:
> >
> > if ( (n & j) == j ) {
> > buffer[i] = '1';
> > }
> > else {
> > buffer[i] = '0';
> > }

>
> I agree that to some it's more readable, but as it's more lines of code, and
> duplicates the assignment etc, I think it's more prone to errors later -
> like if someone changes it.


Why not just: buffer[i] = (n & j) == j;
?


Sorry, an error. Should be: buffer[i] = ((n & j) == j) + '0';
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Dec 19 '05 #26

P: n/a
Dik T. Winter wrote:

In article <dn**********@news.ox.ac.uk> "rayw"
<ra*********@gmail.com> writes:
> "Pieter Droogendijk" <pi******@binkySPAM.orgFOR.ukME>
> wrote in message
> news:pa****************************@binkySPAM.orgF OR.ukME...
> > On Tue, 13 Dec 2005 10:21:09 +0000, rayw wrote: ... > >> buffer[i] = (n & j) == j ? '1' : '0';
> >
> > This expression could be nicer. How's this:
> >
> > if ( (n & j) == j ) {
> > buffer[i] = '1';
> > }
> > else {
> > buffer[i] = '0';
> > }

>
> I agree that to some it's more readable,
> but as it's more lines of code, and
> duplicates the assignment etc,
> I think it's more prone to errors later -
> like if someone changes it.


Why not just: buffer[i] = (n & j) == j;
?


The above examples indicate that he wants
either a '1' or '0' in buffer[i],
rather than either a 1 or 0.

--
pete
Dec 19 '05 #27

P: n/a
Mark McIntyre <ma**********@spamcop.net> writes:
On 14 Dec 2005 03:51:59 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(comparison of using if/else or ?: for assigning to buffer[i])
If Mr. McIntyre says he
finds the if/else form with two assignments more readable, I'm expect
that's so, but his reaction isn't shared by everyone.


Of course. Some people /like/ obfuscated code :-)


Everyone's entitled to an opinion. IME, however, those
who express opinions and little else, and who don't bother
to differentiate between what is opinion and what is fact,
rarely say anything worth listening to.
Dec 28 '05 #28

P: n/a
Tim Rentsch wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
Tim Rentsch <tx*@alumnus.caltech.edu> wrote:

(comparison of using if/else or ?: for assigning to buffer[i])
If Mr. McIntyre says he finds the if/else form with two
assignments more readable, I'm expect that's so, but his
reaction isn't shared by everyone.


Of course. Some people /like/ obfuscated code :-)


Everyone's entitled to an opinion. IME, however, those who
express opinions and little else, and who don't bother to
differentiate between what is opinion and what is fact, rarely
say anything worth listening to.


In these style matters, all is opinion. The fact is that the
opinions vary in close correlation with the language flavor on
which one has been brought up. Users of languages without esoteric
symbol reuse (such as Pascal) will almost always eschew funny
statements involving question marks and colons. In the long run it
shouldn't matter, since a moderately intelligent compiler will
produce the same object code for either style.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 28 '05 #29

P: n/a
On Wed, 28 Dec 2005 15:52:58 -0500, in comp.lang.c , "Chuck F. "
<cb********@yahoo.com> wrote:
Tim Rentsch wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
Of course. Some people /like/ obfuscated code :-)
Everyone's entitled to an opinion.


In these style matters, all is opinion.

....In the long run it
shouldn't matter, since a moderately intelligent compiler will
produce the same object code for either style.


I guess my /opinion/ is that you don't write code to be legible by
the compiler, but by the maintenance droid in 3 years time. And for
anyone who says maintenance droids ought to be smart enough to figure
out your code, I direct your attention to the sig below.

Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 28 '05 #30

P: n/a

Mark McIntyre schreef:
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan


Words to code by.

Dec 29 '05 #31

P: n/a
Mark McIntyre wrote:
"Chuck F. " <cb********@yahoo.com> wrote:
Tim Rentsch wrote:
Mark McIntyre <ma**********@spamcop.net> writes: Of course. Some people /like/ obfuscated code :-)

Everyone's entitled to an opinion.


In these style matters, all is opinion.

....
In the long run it shouldn't matter, since a moderately
intelligent compiler will produce the same object code for
either style.


I guess my /opinion/ is that you don't write code to be legible
by the compiler, but by the maintenance droid in 3 years time.
And for anyone who says maintenance droids ought to be smart
enough to figure out your code, I direct your attention to the
sig below.


My, you got out of the wrong side of the bed this morning. Has the
cat recovered from the kicking? I didn't even take a position on
which code style was preferable, just pointed out the background
that influences the choice. You snipped that part.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 29 '05 #32

P: n/a
On Wed, 28 Dec 2005 18:55:44 -0500, in comp.lang.c , "Chuck F. "
<cb********@yahoo.com> wrote:
Mark McIntyre wrote:
(stuff which chuck interpreted as a diatribe against him (if one can
have a personal diatribe) but which wasn't)
My, you got out of the wrong side of the bed this morning. Has the
cat recovered from the kicking?
Its Christmas. I've had to suffer a week of all three children in
hyperdrive mode, the aged relatives in dribble mode, and several wooly
jumpers from my aunties.... :-(
I didn't even take a position on
which code style was preferable, just pointed out the background
that influences the choice. You snipped that part.


Actually I didn't intend anything I said as any sort of attack on what
you said, I was merely stating my opinion.
Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 30 '05 #33

P: n/a
"Chuck F. " <cb********@yahoo.com> writes:
Tim Rentsch wrote:
Mark McIntyre <ma**********@spamcop.net> writes:
Tim Rentsch <tx*@alumnus.caltech.edu> wrote:

(comparison of using if/else or ?: for assigning to buffer[i])

If Mr. McIntyre says he finds the if/else form with two
assignments more readable, I'm expect that's so, but his
reaction isn't shared by everyone.

Of course. Some people /like/ obfuscated code :-)
Everyone's entitled to an opinion. IME, however, those who
express opinions and little else, and who don't bother to
differentiate between what is opinion and what is fact, rarely
say anything worth listening to.


In these style matters, all is opinion. [snip]


In discussing questions about style, some people express
only opinion. But that doesn't mean opinion is all there
is. For example, doing bracing this way

if(...)
{
...
}

rather than this way

if(...){
...
}

takes more vertical space. (Or, if someone prefers, the
second form takes less vertical space.) That observation is
a fact. As another example, consider these alternatives for
placing close braces (open braces omitted):

if(...)
...
...
...
}
if(...)
...
...
...
}

Studies have been done that show the second form results in
fewer errors. That is another fact (ie, that the studies
reported those results).

How pertinent such facts are, and how much weight (and on
which side of the scale) should be given to them, depends on
the situation, and different people - or different
circumstances - may very well arrive at different
conclusions. Even so, unless some statements of fact are
included in the discussion, the discussion is usually not
very fruitful. "I think X." "I think Y." "So what?" "So
what?"

In the long run it
shouldn't matter, since a moderately intelligent compiler will
produce the same object code for either style.


I have to admit I didn't see this one coming. Surely most
people have other and better metrics for code quality than
only what object code is produced.
Dec 30 '05 #34

P: n/a
On 29 Dec 2005 20:02:04 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(of other different bracing examples)
Studies have been done that show the second form results in
fewer errors.
Studies also recently showed that twice as many people would jump off
a ship to rescue their hat as would do it to rescue their spouse. That
doesn't mean its true... :-)
That is another fact (ie, that the studies
reported those results).


Indeed, its a fact that a study has been done. :-)
Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 30 '05 #35

P: n/a
On Fri, 30 Dec 2005 12:13:40 +0000, Mark McIntyre
<ma**********@spamcop.net> wrote:
On 29 Dec 2005 20:02:04 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(of other different bracing examples)
Studies have been done that show the second form results in
fewer errors.
Studies also recently showed that twice as many people would jump off
a ship to rescue their hat as would do it to rescue their spouse. That
doesn't mean its true... :-)


I would be interested if both of you provided some references to these
studies.
That is another fact (ie, that the studies
reported those results).


Indeed, its a fact that a study has been done. :-)
Mark McIntyre


--
Al Balmer
Sun City, AZ
Dec 30 '05 #36

P: n/a
Al Balmer <al******@att.net> writes:

[edited for brevity]
On 29 Dec 2005 20:02:04 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(of other different bracing examples)
Studies have been done that show the second form results in
fewer errors.


I would be interested if you provided some references to these
studies.


I'm sorry to report that I don't have a reference. It's something I
remember reading at some point, but that was before I started keeping
track of references to such things. It's unfortunate, because I think
the programming community would benefit from doing more studies on
these kinds of issues and accumulating references to them.
Dec 30 '05 #37

P: n/a
On Fri, 30 Dec 2005 09:08:39 -0700, in comp.lang.c , Al Balmer
<al******@att.net> wrote:
I would be interested if both of you provided some references to these
studies.


The hat/spouse thing was printed in The Week, which is a UK magazine
summarising the best of each week's UK and world press. The survey was
apparently originally printed in the Daily Mail. Those of you who know
the Mail will infer from this what you will.... .
Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 30 '05 #38

P: n/a
On Fri, 30 Dec 2005 23:45:36 +0000, Mark McIntyre
<ma**********@spamcop.net> wrote:
On Fri, 30 Dec 2005 09:08:39 -0700, in comp.lang.c , Al Balmer
<al******@att.net> wrote:
I would be interested if both of you provided some references to these
studies.


The hat/spouse thing was printed in The Week, which is a UK magazine
summarising the best of each week's UK and world press. The survey was
apparently originally printed in the Daily Mail. Those of you who know
the Mail will infer from this what you will.... .
Mark McIntyre


Thanks. Confirms my guess about the reliability of the information.

--
Al Balmer
Sun City, AZ
Jan 3 '06 #39

P: n/a
On Tue, 03 Jan 2006 09:12:19 -0700, in comp.lang.c , Al Balmer
<al******@att.net> wrote:
On Fri, 30 Dec 2005 23:45:36 +0000, Mark McIntyre
<ma**********@spamcop.net> wrote:
The survey was
apparently originally printed in the Daily Mail. Those of you who know
the Mail will infer from this what you will.... .


Thanks. Confirms my guess about the reliability of the information.


.... which was sorta my point about the original topic - vis that
contextless survey results quoted 2nd or 3rd hand are as worthwhile as
articles in tabloid newspapers. ...
Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Jan 3 '06 #40

P: n/a

In article <kf*************@alumnus.caltech.edu>, Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Al Balmer <al******@att.net> writes:
On 29 Dec 2005 20:02:04 -0800, in comp.lang.c , Tim Rentsch
<tx*@alumnus.caltech.edu> wrote:

(of other different bracing examples)

>Studies have been done that show the second form results in
>fewer errors.


I would be interested if you provided some references to these
studies.


I'm sorry to report that I don't have a reference. It's something I
remember reading at some point, but that was before I started keeping
track of references to such things. It's unfortunate, because I think
the programming community would benefit from doing more studies on
these kinds of issues and accumulating references to them.


Derek M Jones' _The New C Standard_[1] has an extended discussion on
source code readability with considerable reference to studies of
human vision, reading, and so forth. See the commentary on sentence
766 (the beginning of 6.4 in the Standard), which is PDF page 682 in
the version I have (1.0b). He notes:

Unfortunately there are no studies, using experienced developers,
that compare the effects of different source code layout on reading
performance. Becoming an experienced developer can be said to involve
learning to read source that has been laid out in a number of
different ways. The visually based guidelines in this book do not
attempt to achieve an optimum layout, rather they attempt to steer
developers away from layouts that are likely to be have high error
rates. (688)

He later discusses opening brace position and claims that "[t]here
are several reasons for believing that [placing the opening brace on
the same line as other non-white-space characters] results in a
larger number of mistakes being made than [placing it on a line by
itself]", but goes on to note that "[g]iven the lack of experimental
measurements of reading performance for different layout schemes,
there is no empirical evidence to support any guideline
recommendation relating to the visual layout of blocks" (1387).

I have to say that I find Jones' argument rather more persuasive than
a casual description of something someone remembers reading once some
time ago. It may be a fact that some study at some time concluded
that closing brace position X produced a lower error rate among
readers than did closing brace position Y; but at this point it's no
more than an assertion, and even if it is a fact, we lack any basis
on which to judge the study's usefulness. (For example, Jones
provides significant evidence to support the theory that practice
in reading a particular style considerably dominates any effect
inherent in that style. A study that failed to account for that in
some fashion would be useless.)

All that said, even if Tim's example was perhaps infelicitous, I take
his overall point: there are matters of fact relevant to questions of
style.
1. http://www.knosof.co.uk/cbook/cbook.html

--
Michael Wojcik mi************@microfocus.com

Bohemia is only a stage in a man's life, except in the case of fools and
a very few others. It is not a profession. -- Arthur Ransome
Jan 4 '06 #41

This discussion thread is closed

Replies have been disabled for this discussion.