473,325 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

print binary

hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new to
C.

#include<stdio.h>
#include<math.h>
main()
{
int val,npow;
printf("enter value:");
scanf("%d",&val);
for(npow=31;npow>-1;--npow){
if(val&pow(2,npow))putchar(1);
else putchar(0);
}
}
Jun 27 '08 #1
36 3991
In article <g3**********@aioe.org>,
Kapteyn's Star <in*****@invalid.invalidwrote:
hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function 'main':
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new to
C.

#include<stdio.h>
#include<math.h>
main()
{
int val,npow;
printf("enter value:");
scanf("%d",&val);
for(npow=31;npow>-1;--npow){
if(val&pow(2,npow))putchar(1);
else putchar(0);
}
}
Among other problems, it looks as though you're trying to "be too
clever"...

Break it down further into individual steps instead of trying to be so
"clever" by cramming it all on one basically unreadable line. Whitespace
is free and unlimited, and makes a world of difference in readability.
Which, in turn, makes trying to spot problems easier. Ditto local
variables for intermediate steps.

for (npow=...)
{
PowerVal = pow(2, npow);
TheBit = val & PowerVal;
if (TheBit)
putchar('1');
else
putchar('0');
}
etc...

One of the "other problems":
"putchar(1)" is going to try to print the character represented by ASCII
code 1, which is almost guaranteed to NOT be "the digit 1", as you're
hoping for... I'm betting what actually comes out will be either some
unreadable graphic char, or an invisible representation of "Control-A",
but exactly what will get printed is going to be platform dependent.

You're also assuming that an int is 32 bits long. Which isn't always
true, and can land you in a world of "Why isn't this working?!?!?"
hurt...

--
Don Bruder - da****@sonic.net - If your "From:" address isn't on my whitelist,
or the subject of the message doesn't contain the exact text "PopperAndShadow"
somewhere, any message sent to this address will go in the garbage without my
ever knowing it arrived. Sorry... <http://www.sonic.net/~dakiddfor more info
Jun 27 '08 #2
On Jun 20, 12:49*am, Kapteyn's Star <inva...@invalid.invalidwrote:
hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new to
C.

#include<stdio.h>
#include<math.h>
main()
{
* * int val,npow;
* * printf("enter value:");
* * scanf("%d",&val);
* * for(npow=31;npow>-1;--npow){
* * * * if(val&pow(2,npow))putchar(1);
* * * * else putchar(0);
* * }

}

The pow() function returns a double value, the binary & operator works
only with integer operators. You can cast the return value of pow()
to int, or use a more efficient method to do your bit checking. Your
putchar calls should be changed to putchar('1') and putchar('0')
respectively, putchar(1) will print the character with the numeric
value of 1 as opposed to the character that represents the number 1.
You should also print a newline at the end out your output. You
should have a correct prototype for main() and a little more liberal
use of whitespace would be welcome. Here is a revised version:

#include <stdio.h>
#include <math.h>

int main(void)
{
int val, npow;

printf("enter value: ");
scanf("%d", &val);

for (npow = 31; npow -1; --npow) {
(val & (int) pow(2, npow)) ? putchar('1') : putchar('0');
}
putchar('\n');

return 0;
}

Like the original, this assumes a 32-bit int and the multiple calls to
pow() are very inefficient. Instead of "val & (int) pow(2, npow)" try
"val & 1<<npow".

--
Robert Gamble
Jun 27 '08 #3
Kapteyn's Star wrote, On 20/06/08 05:49:
hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new to
C.

#include<stdio.h>
#include<math.h>
Since we moved away from punched cards spaces have been cheap. Using a
few more will make your code a lot more readable.

#include <stdio.h>
#include <math.h>
main()
Implicit int (which you use above) is gone from the latest C standard.
Not many compilers support the latest C standard fully, but why break
compatibility just to save a very small amount of typing? Also better to
be eplicit about no parameters.

int main(void)
{
int val,npow;
printf("enter value:");
There is no guarantee that the above will be printed immediately due to
line buffering. You should flush stdout here.
scanf("%d",&val);
scanf is generally a poor choice of function for user input. Better to
use fgets and then pass the entered line possibly using sscanf. Whatever
you use you should check the value returned by the input function.
for(npow=31;npow>-1;--npow){
int could be either more or less than 32 bits.
if(val&pow(2,npow))putchar(1);
Lets space the above out so it is actually possible to read it.
if (val & pow(2,npow)) putchar(1);

OK, the "&" above is the only one on the line so it must be something to
do with that. Look up "&" in your text book and you will find it works
on integer types only. Loop up pow and you will find it returns a double
(i.e. something other than an integer type).

Actually, you should look at using the shift operator instead of using pow.
else putchar(0);
}
}
--
Flash Gordon
Jun 27 '08 #4
In a4**********************************...oglegroups.com,
Robert Gamble (Thu, 19 Jun 2008 22:19:23 -0700):
On Jun 20, 12:49Â*am, Kapteyn's Star <inva...@invalid.invalidwrote:
>hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new
to C.

#include<stdio.h>
#include<math.h>
main()
{
Â* Â* int val,npow;
Â* Â* printf("enter value:");
Â* Â* scanf("%d",&val);
Â* Â* for(npow=31;npow>-1;--npow){
Â* Â* Â* Â* if(val&pow(2,npow))putchar(1);
Â* Â* Â* Â* else putchar(0);
Â* Â* }

}
The pow() function returns a double value, the binary & operator works
only with integer operators. You can cast the return value of pow() to
int, or use a more efficient method to do your bit checking. Your
putchar calls should be changed to putchar('1') and putchar('0')
respectively, putchar(1) will print the character with the numeric value
of 1 as opposed to the character that represents the number 1. You
should also print a newline at the end out your output. You should have
a correct prototype for main() and a little more liberal use of
whitespace would be welcome. Here is a revised version:

#include <stdio.h>
#include <math.h>

int main(void)
{
int val, npow;

printf("enter value: ");
scanf("%d", &val);

for (npow = 31; npow -1; --npow) {
(val & (int) pow(2, npow)) ? putchar('1') : putchar('0');
}
putchar('\n');

return 0;
}

Like the original, this assumes a 32-bit int and the multiple calls to
pow() are very inefficient. Instead of "val & (int) pow(2, npow)" try
"val & 1<<npow".
thanks a lot! but i don't understand one thing. the program gives the
same bits for input = 2^31 and 2^31-1. only the correct value for 2^31 is
printed for -2^31. can any one explain why?

again thanks very much.
Jun 27 '08 #5
In t9************@news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun 2008
06:54:35 +0100):

In t9************@news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun 2008
06:54:35 +0100):
Kapteyn's Star wrote, On 20/06/08 05:49:
>hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only new
to C.

#include<stdio.h>
#include<math.h>

Since we moved away from punched cards spaces have been cheap. Using a
few more will make your code a lot more readable.

#include <stdio.h>
#include <math.h>
>main()

Implicit int (which you use above) is gone from the latest C standard.
Not many compilers support the latest C standard fully, but why break
compatibility just to save a very small amount of typing? Also better to
be eplicit about no parameters.

int main(void)
okay. my textbook actually uses "int main()" but i wrote main to save
space. is int main() better or int main(void) is better? what is the
differance between them?
>{
int val,npow;
printf("enter value:");

There is no guarantee that the above will be printed immediately due to
line buffering. You should flush stdout here.
> scanf("%d",&val);

scanf is generally a poor choice of function for user input. Better to
use fgets and then pass the entered line possibly using sscanf. Whatever
you use you should check the value returned by the input function.
> for(npow=31;npow>-1;--npow){

int could be either more or less than 32 bits.
my book mentions int is 4 bytes. If it is less or more then what should I
do. I should look at sizeof(int) and set npow to 15 if it return 2 and 63
if it return 8?
> if(val&pow(2,npow))putchar(1);

Lets space the above out so it is actually possible to read it.
if (val & pow(2,npow)) putchar(1);

OK, the "&" above is the only one on the line so it must be something to
do with that. Look up "&" in your text book and you will find it works
on integer types only. Loop up pow and you will find it returns a double
(i.e. something other than an integer type).
Sorry. i read about it and forgot. I will cast pow to int.
Actually, you should look at using the shift operator instead of using
pow.
Okay, i'm not yet at shift ops but i will write a shifted version.
> else putchar(0);
}
}
thanks for all your advice.
Jun 27 '08 #6
Kapteyn's Star wrote:
In t9************@news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun
2008 06:54:35 +0100):

In t9************@news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun
2008 06:54:35 +0100):
>>main()

Implicit int (which you use above) is gone from the latest C
standard. Not many compilers support the latest C standard fully,
but why break compatibility just to save a very small amount of
typing? Also better to be eplicit about no parameters.

int main(void)

okay. my textbook actually uses "int main()" but i wrote main to save
space. is int main() better or int main(void) is better? what is the
differance between them?
int main() is required by the latest standard which dropped the implicit
int.
int main(void) is better as it tells the compiler as well as the human
reader that there won't be any arguments
>>{
int val,npow;
printf("enter value:");

There is no guarantee that the above will be printed immediately due
to line buffering. You should flush stdout here.
>> scanf("%d",&val);

scanf is generally a poor choice of function for user input. Better
to use fgets and then pass the entered line possibly using sscanf.
Whatever you use you should check the value returned by the input
function.
>> for(npow=31;npow>-1;--npow){

int could be either more or less than 32 bits.

my book mentions int is 4 bytes. If it is less or more then what
Then your book is wrong or tied to a certain implementation.
should I do. I should look at sizeof(int) and set npow to 15 if it
return 2 and 63 if it return 8?
to be on the safe sideuse

#include <limits.h>
sizeof(int) * CHAR_BIT - 1

Bye, Jojo
Jun 27 '08 #7
In g3**********@aioe.org, Kapteyn's Star (Fri, 20 Jun 2008 06:49:05
+0200):

After following what every one has adviced i wrote the code below. i
tested it for many values and binary conversion is ok but strtoul seems
to give wrong answers. where could be the problem? i have copied out a
session here.

../printbin 0
You entered: 0 (hex: 0).
binary: 00000000000000000000000000000000

../printbin 1
You entered: 0 (hex: 0).
binary: 00000000000000000000000000000001

../printbin 10
You entered: 0 (hex: 0).
binary: 00000000000000000000000000001010

../printbin 0xffffffff
You entered: 4294967040 (hex: ffffff00).
binary: 11111111111111111111111111111111

../printbin 0xfffffff0
You entered: 4294967040 (hex: ffffff00).
binary: 11111111111111111111111111110000

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void ui2bstr(unsigned long val, char *buf) {
int bitpos;
for(bitpos=sizeof(unsigned long)*CHAR_BIT-1; bitpos >= 0; bitpos--) {
if(val & (1UL << bitpos)) {
buf[(sizeof(unsigned long)*CHAR_BIT-1)-bitpos] = '1';
}
else {
buf[(sizeof(unsigned long)*CHAR_BIT-1)-bitpos] = '0';
}
}
buf[sizeof(unsigned long)*CHAR_BIT] = '\0';
}
int main(int argc, char *argv[]) {
unsigned long num=strtoul(argv[1], NULL, 0);
char buf[sizeof(unsigned long)*CHAR_BIT];

ui2bstr(num,buf);
printf("You entered: %lu (hex: %lx).\nbinary: %s\n",num,num,buf);
}
Jun 27 '08 #8
In g3**********@aioe.org, Kapteyn's Star (Fri, 20 Jun 2008 10:11:15
+0200):

very sorry for not saying before my compiler is gcc(4.1.0) and glibc
(2.3.6).
Jun 27 '08 #9
Flash Gordon wrote:
Kapteyn's Star wrote:
.... snip ...
>
> scanf("%d",&val);

scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

if (1 != scanf("%d, &val)) {
/* failure, do something about it */
}
else {
/* success, you can use val */
/* but remember there is unused data in the stdin line */
}

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #10
On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
thanks a lot! but i don't understand one thing. the program gives the
same bits for input = 2^31 and 2^31-1. only the correct value for 2^31 is
printed for -2^31. can any one explain why?
Integers in C are stored using the 2s complement system. This means that
the most signficant bit is a sign bit: it's 1 for negative numbers and 0
for non-negative numbers. On your system, an int is 32 bits, which means
that you can store numbers from (-2^31) to (2^31 - 1) inclusive.

The bit pattern of 2^31 is a 1 in the sign bit, followed by zeros. In
the 2s complement system, this represents the largest negative number,
namely -2^31.

If you change val to be an unsigned int rather than an int (and change
the scanf format specifier to %u), then you'll be able to deal with
numbers between 0 and (2^32-1) inclusive.

By the way, using pow() is a /really/ bad way to calculate small powers
of 2: follow the suggestion elsewhere in the thread and use (1<<npow)
instead. This is likely to translate to a single instruction in the
compiled machine code.

Jun 27 '08 #11

"Kapteyn's Star" <re*************************************@g0m8ai2l. 9com>
wrote in message news:g3**********@aioe.org...
In g3**********@aioe.org, Kapteyn's Star (Fri, 20 Jun 2008 06:49:05
+0200):

After following what every one has adviced i wrote the code below. i
tested it for many values and binary conversion is ok but strtoul seems
to give wrong answers. where could be the problem? i have copied out a
session here.
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void ui2bstr(unsigned long val, char *buf) {
int bitpos;
for(bitpos=sizeof(unsigned long)*CHAR_BIT-1; bitpos >= 0; bitpos--) {
if(val & (1UL << bitpos)) {
buf[(sizeof(unsigned long)*CHAR_BIT-1)-bitpos] = '1';
}
else {
buf[(sizeof(unsigned long)*CHAR_BIT-1)-bitpos] = '0';
}
}
buf[sizeof(unsigned long)*CHAR_BIT] = '\0';
}
int main(int argc, char *argv[]) {
unsigned long num=strtoul(argv[1], NULL, 0);
This crashes for me when no arguments are given. Check that argc is at least
2.
char buf[sizeof(unsigned long)*CHAR_BIT];
For 32 bits for example you will need 33 characters to allow for the
terminator. So an extra char is needed.

BTW (unsigned long)*CHAR_BIT is a little unwieldly to keep writing (5 times
above); perhaps put into a macro.
>
ui2bstr(num,buf);
printf("You entered: %lu (hex: %lx).\nbinary: %s\n",num,num,buf);
}
--
Bartc
Jun 27 '08 #12
Antoninus Twink wrote:
On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
>thanks a lot! but i don't understand one thing. the program gives the
same bits for input = 2^31 and 2^31-1. only the correct value for
2^31 is printed for -2^31. can any one explain why?

Integers in C are stored using the 2s complement system.
Wrong, they are at best likely to be stored in 2s complement, but 1s
compelent is also possible. All depends on the implementation

Bye, Jojo
Jun 27 '08 #13
In xo******************@text.news.virginmedia.com, Bartc (Fri, 20 Jun 2008
09:04:29 +0000):

Thanks Bartc, making buf to 33 chars fixed the problem! i also did as you
said and created a marco as follows:-

#define UL_BITS (sizeof(unsigned long)*CHAR_BIT)

everything seems ok now. thanks to everyone.
Jun 27 '08 #14
In sl*******************@nospam.invalid, Antoninus Twink (Fri, 20 Jun 2008
08:58:59 +0000):

In sl*******************@nospam.invalid, Antoninus Twink (Fri, 20 Jun 2008
08:58:59 +0000):
On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
>thanks a lot! but i don't understand one thing. the program gives the
same bits for input = 2^31 and 2^31-1. only the correct value for 2^31
is printed for -2^31. can any one explain why?

Integers in C are stored using the 2s complement system. This means that
the most signficant bit is a sign bit: it's 1 for negative numbers and 0
for non-negative numbers. On your system, an int is 32 bits, which means
that you can store numbers from (-2^31) to (2^31 - 1) inclusive.

The bit pattern of 2^31 is a 1 in the sign bit, followed by zeros. In
the 2s complement system, this represents the largest negative number,
namely -2^31.
I think i'm getting it. all bit pattern with top most bit is 0 are
positive values and 0 and those wih top bit of 1 are negative values. is
this ok? i find the scheme where top bit is sign bit to be simpler to
understand.
If you change val to be an unsigned int rather than an int (and change
the scanf format specifier to %u), then you'll be able to deal with
numbers between 0 and (2^32-1) inclusive.

By the way, using pow() is a /really/ bad way to calculate small powers
of 2: follow the suggestion elsewhere in the thread and use (1<<npow)
instead. This is likely to translate to a single instruction in the
compiled machine code.
i have included another version with these improvments in another post.

thanks for the info!
Jun 27 '08 #15
Kapteyn's Star wrote:
>
After following what every one has adviced i wrote the code below.
i tested it for many values and binary conversion is ok but strtoul
seems to give wrong answers. where could be the problem? i have
copied out a session here.
I corrected the source, mainly to insert reasonable white space.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

void ui2bstr(unsigned long val, char *buf) {
int bitpos;

for (bitpos = sizeof(unsigned long) * CHAR_BIT - 1;
bitpos >= 0;
bitpos--) {
if (val & (1UL << bitpos)) {
buf[(sizeof(unsigned long) * CHAR_BIT - 1) - bitpos] =
'1';
}
else {
buf[(sizeof(unsigned long) * CHAR_BIT - 1) - bitpos] =
'0';
}
}
buf[sizeof(unsigned long) * CHAR_BIT] = '\0';
} /* ui2bstr */

int main(int argc, char *argv[]) {
unsigned long num = strtoul(argv[1], NULL, 0);
char buf[sizeof(unsigned long) * CHAR_BIT];

ui2bstr(num, buf);
printf("You entered: %lu (hex: %lx).\nbinary: %s\n",
num, num, buf);
return 0;
} /* main */

and the result shows no errors.

[1] c:\c\junk>cc junk.c
junk.c: In function `main':
junk.c:21: warning: unused parameter `argc'

[1] c:\c\junk>a 0xffffff00
You entered: 4294967040 (hex: ffffff00).
binary: 11111111111111111111111100000000

[1] c:\c\junk>a 0xfffffff0
You entered: 4294967280 (hex: fffffff0).
binary: 11111111111111111111111111110000

[1] c:\c\junk>a 0xffffffff
You entered: 4294967295 (hex: ffffffff).
binary: 11111111111111111111111111111111

[1] c:\c\junk>a 0x7ffffff
You entered: 134217727 (hex: 7ffffff).
binary: 00000111111111111111111111111111

I suspect you have a library fault.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

** Posted from http://www.teranews.com **
Jun 27 '08 #16
Kapteyn's Star wrote:
hi group,
i try to compile code below but my compiler is failing. it
tells:- printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able
to understand what it mean. how to correct fault? please help
i'm only new to C.

#include<stdio.h>
#include<math.h>
main()
{
int val,npow;
printf("enter value:");
scanf("%d",&val);
for(npow=31;npow>-1;--npow){
if(val&pow(2,npow))putchar(1);
else putchar(0);
}
}
The major problem you got here is, that pow returns a floating
point variable. And if I'm not mistaken, the binary and may
operator on the binary representation of the floating point
variable, which is of course not, what you want.

So for god's sake, why, oh why, can't people not simply use the
right tools. Using pow to select a single bit is like using
multiplication and division for the same task - I've actually
seen this done in a some of programs, most notably in code
written by mathematicans here at the university.

Ok, once and for all: There are the bit shift operators: "<<"
and ">>". USE THEM!

then the code would look like this:

void putbin(int a)
{
int i = sizeof(int) * 8; /* assuming 8 bits for a char */
while(i---) {
putchar( a & ( 1 << i ) ? '1' : '0');
}
}

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867

Jun 27 '08 #17
CBFalconer wrote:
Kapteyn's Star wrote:
>>
After following what every one has adviced i wrote the code below.
i tested it for many values and binary conversion is ok but strtoul
seems to give wrong answers. where could be the problem? i have
copied out a session here.

I corrected the source, mainly to insert reasonable white space.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

void ui2bstr(unsigned long val, char *buf) {
int bitpos;

for (bitpos = sizeof(unsigned long) * CHAR_BIT - 1;
bitpos >= 0;
bitpos--) {
if (val & (1UL << bitpos)) {
buf[(sizeof(unsigned long) * CHAR_BIT - 1) - bitpos] =
'1';
}
else {
buf[(sizeof(unsigned long) * CHAR_BIT - 1) - bitpos] =
'0';
}
}
buf[sizeof(unsigned long) * CHAR_BIT] = '\0';
Here you write past the end of buf[]
} /* ui2bstr */

int main(int argc, char *argv[]) {
unsigned long num = strtoul(argv[1], NULL, 0);
char buf[sizeof(unsigned long) * CHAR_BIT];
Still no space for the terminating '\0'
>
ui2bstr(num, buf);
printf("You entered: %lu (hex: %lx).\nbinary: %s\n",
num, num, buf);
return 0;
} /* main */

and the result shows no errors.
pure luck, see above
[1] c:\c\junk>cc junk.c
junk.c: In function `main':
junk.c:21: warning: unused parameter `argc'

[1] c:\c\junk>a 0xffffff00
You entered: 4294967040 (hex: ffffff00).
binary: 11111111111111111111111100000000

[1] c:\c\junk>a 0xfffffff0
You entered: 4294967280 (hex: fffffff0).
binary: 11111111111111111111111111110000

[1] c:\c\junk>a 0xffffffff
You entered: 4294967295 (hex: ffffffff).
binary: 11111111111111111111111111111111

[1] c:\c\junk>a 0x7ffffff
You entered: 134217727 (hex: 7ffffff).
binary: 00000111111111111111111111111111

I suspect you have a library fault.
Nope. Undefined behavoir...

Bye, Jojo
Jun 27 '08 #18
Wolfgang Draxinger wrote:
Ok, once and for all: There are the bit shift operators: "<<"
and ">>". USE THEM!

then the code would look like this:

void putbin(int a)
{
int i = sizeof(int) * 8; /* assuming 8 bits for a char */
why assuming rather than getting it right and use CHAR_BIT?
And while at t, I'd change it to
int i= sizeof a * CHAR_BIT;
so it continues to work if changing
void putbin(int a)
to e.g.
void putbin (long long int a)
while(i---) {
There's a - too many
putchar( a & ( 1 << i ) ? '1' : '0');
}
}

Wolfgang Draxinger
Bye, Jojo
Jun 27 '08 #19
On 20 Jun 2008 at 9:34, Kapteyn's Star wrote:
In sl*******************@nospam.invalid, Antoninus Twink (Fri, 20 Jun 2008
08:58:59 +0000):
>The bit pattern of 2^31 is a 1 in the sign bit, followed by zeros. In
the 2s complement system, this represents the largest negative number,
namely -2^31.

I think i'm getting it. all bit pattern with top most bit is 0 are
positive values and 0 and those wih top bit of 1 are negative values. is
this ok? i find the scheme where top bit is sign bit to be simpler to
understand.
It may be simpler for humans to understand, but 2's complement is well
suited to computer arithmetic: it means your processsor can effectively
just do addition etc. mod 2^32, and everything works out right. It would
obviously lead to more complex hardware if you first had to inspect the
sign bit before knowing how addition should work.

Jun 27 '08 #20
Joachim Schmitz wrote:
>
> while(i---) {
There's a - too many
man: bouncing switch...

;-)

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867

Jun 27 '08 #21
Flash Gordon wrote:
Kapteyn's Star wrote, On 20/06/08 05:49:
>hi group,
i try to compile code below but my compiler is failing. it tells:-
printbin.c: In function ‘main’:
printbin.c:9: error: invalid operands to binary & i am not able to
understand what it mean. how to correct fault? please help i'm only
new to
C.

#include<stdio.h>
#include<math.h>

Since we moved away from punched cards spaces have been cheap. Using a
few more will make your code a lot more readable.

#include <stdio.h>
#include <math.h>
>main()

Implicit int (which you use above) is gone from the latest C standard.
Not many compilers support the latest C standard fully, but why break
compatibility just to save a very small amount of typing?
Also, there's never been a standard version of C,
which had both implicit int and also omitted return statement in main.
> else putchar(0);
}
}

--
pete
Jun 27 '08 #22
CBFalconer wrote:
Flash Gordon wrote:
>Kapteyn's Star wrote:
... snip ...
>> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.

Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

if (1 != scanf("%d, &val)) {
/* failure, do something about it */
}
else {
/* success, you can use val */
/* but remember there is unused data in the stdin line */
}
Shouldn't the comments be more like this way?

if (1 != scanf("%d", &val)) {
/* failure, do something about it */
/* but remember there is unused data in the stdin line */
}
else {
/* success, you can use val */
}

--
pete
Jun 27 '08 #23
In article <g3**********@aioe.org>
Kapteyn's Star <re*************************************@g0m8ai2l. 9comwrote:
>I think i'm getting it. all bit pattern with top most bit is 0 are
positive values and 0 and those wih top bit of 1 are negative values.
Yes, but "top bit" is an overstatement: C requires only that *some*
particular bit be a "sign bit". (It is nearly universally the
most-significant bit, which is the "top" one if you write them
most-significant-first and call the first one you write the "top"
one. If you were to write numbers left-to-right, as we do, but
read right-to-left, as they do in parts of the Middle East, would
you still think of the left-most bit as the "first"? In parts of
the Orient, where they write from the top down, you would be on
much more solid ground.)

You might also take a look at <http://web.torek.net/torek/c/numbers.html>.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Jun 27 '08 #24
pete wrote:
CBFalconer wrote:
.... snip ...
>
>Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

if (1 != scanf("%d, &val)) {
/* failure, do something about it */
}
else {
/* success, you can use val */
/* but remember there is unused data in the stdin line */
}

Shouldn't the comments be more like this way?

if (1 != scanf("%d", &val)) {
/* failure, do something about it */
/* but remember there is unused data in the stdin line */
}
else {
/* success, you can use val */
}
No, but maybe that line should appear in both sections. The point
is that scanf leaves all characters after the integer, which always
means at least the '\n', in the system. It is useful to have a
routine around to remove the remainder of any line, such as:

int clearln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f)) && ('\n' != ch)) continue;
return ch;
}

For example, you may want to use some default value when an integer
doesn't appear, and the rest of the line is satisfactory for your
purpose. So the line clearing should not be part of the integer
getting.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #25
Joachim Schmitz wrote:
CBFalconer wrote:
>Kapteyn's Star wrote:
>>>
After following what every one has adviced i wrote the code
below. i tested it for many values and binary conversion is
ok but strtoul seems to give wrong answers. where could be
the problem? i have copied out a session here.
.... snip ...
> }
buf[sizeof(unsigned long) * CHAR_BIT] = '\0';

Here you write past the end of buf[]
Ah yes. I missed that mistake. Good catch.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #26
CBFalconer wrote, On 20/06/08 09:41:
Flash Gordon wrote:
>Kapteyn's Star wrote:
... snip ...
>> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.

Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.
I said poor choice rather than unsafe.
if (1 != scanf("%d, &val)) {
/* failure, do something about it */
Which means you normally now have the added complication of reading
through the erroneous input to remove it before it is sensible to try
reading it again.
}
else {
/* success, you can use val */
/* but remember there is unused data in the stdin line */
Another complication.
}
Most people in my experience, particularly inexperienced people, will
find it easier to do:
attempt to read line
If read failed print error
Else
Attempt to decode
If decode failed print error
Else use value

This is because as you well know these little simple programs then tend
to be enhanced and expanded with a loop round the input/error checking
and subsequent inputs later.
--
Flash Gordon
Jun 27 '08 #27
CBFalconer <cb********@yahoo.comwrites:
Flash Gordon wrote:
Kapteyn's Star wrote:
... snip ...
scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.

Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.
[...]

Alas, this is not true; there's no reliable way to check for overflow.

C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the result
of the conversion cannot be represented in the object, the
behavior is undefined.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #28
Keith Thompson wrote:
CBFalconer <cb********@yahoo.comwrites:
.... snip ...
>>
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.
[...]

Alas, this is not true; there's no reliable way to check for
overflow.

C99 7.19.6.2p10:
If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object,
the behavior is undefined.
Well, here is an extract from some of my code. It doesn't include
helper routines, such as 'ignoreblks', 'skipwhite', and 'flushln'.
This has the advantage of working on streams and needing no
buffers. It should be revised to input an unsigned long. Signed
input calls this.

/*--------------------------------------------------------------
* Read an unsigned value. Signal error for overflow or no
* valid number found. Returns 1 for error, 0 for noerror, EOF
* for EOF encountered before parsing a value.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: This specifically forbids a leading '+' or '-'.
*/
int readxwd(unsigned int *wd, FILE *f)
{
unsigned int value, digit;
int status;
int ch;

#define UWARNLVL (UINT_MAX / 10U)
#define UWARNDIG (UINT_MAX - UWARNLVL * 10U)

value = 0; /* default */
status = 1; /* default error */

ch = ignoreblks(f);

if (EOF == ch) status = EOF;
else if (isdigit(ch)) status = 0; /* digit, no error */

while (isdigit(ch)) {
digit = ch - '0';
if ((value UWARNLVL) ||
((UWARNLVL == value) && (digit UWARNDIG))) {
status = 1; /* overflow */
value -= UWARNLVL;
}
value = 10 * value + digit;
ch = getc(f);
} /* while (ch is a digit) */

*wd = value;
ungetc(ch, f);
return status;
} /* readxwd */

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

Jun 28 '08 #29
On Jun 28, 2:11 am, Keith Thompson <ks...@mib.orgwrote:
CBFalconer <cbfalco...@yahoo.comwrites:
Flash Gordon wrote:
Kapteyn's Star wrote:
... snip ...
> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

[...]

Alas, this is not true; there's no reliable way to check for overflow.

C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the result
of the conversion cannot be represented in the object, the
behavior is undefined.
Are you saying that scanf("%d", &intvariable); is _not_ safe even if
the return value of scanf() is properly checked?
Which input would break it?
Jun 28 '08 #30
vi******@gmail.com wrote:
On Jun 28, 2:11 am, Keith Thompson <ks...@mib.orgwrote:
>CBFalconer <cbfalco...@yahoo.comwrites:
Flash Gordon wrote:
Kapteyn's Star wrote:
... snip ...
> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

[...]

Alas, this is not true; there's no reliable way to check for
overflow.

C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object, the
behavior is undefined.
Are you saying that scanf("%d", &intvariable); is _not_ safe even if
the return value of scanf() is properly checked?
Which input would break it?
An input sequence that would cause overflow upon assignment would break
it. In this case undefined behaviour is invoked, which means that scanf
is free to do anything. It might or might not set errno. That's QoI. A
signal might also be raised.

The only way to detect overflow is to either convert manually or employ
the strto* family of functions.

Jun 28 '08 #31
On Jun 28, 7:42 pm, santosh <santosh....@gmail.comwrote:
vipps...@gmail.com wrote:
On Jun 28, 2:11 am, Keith Thompson <ks...@mib.orgwrote:
CBFalconer <cbfalco...@yahoo.comwrites:
Flash Gordon wrote:
Kapteyn's Star wrote:
... snip ...
> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.
[...]
Alas, this is not true; there's no reliable way to check for
overflow.
C99 7.19.6.2p10:
If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object, the
behavior is undefined.
Are you saying that scanf("%d", &intvariable); is _not_ safe even if
the return value of scanf() is properly checked?
Which input would break it?

An input sequence that would cause overflow upon assignment would break
it. In this case undefined behaviour is invoked, which means that scanf
is free to do anything. It might or might not set errno. That's QoI. A
signal might also be raised.
The only way to detect overflow is to either convert manually or employ
the strto* family of functions.
What about this: scanf("%4d", &inttype);
Surely that's safe, is it not?
I always thought scanf() could detect/avoid overflow. I start to
dislike scanf and friends.
Jun 28 '08 #32
vi******@gmail.com wrote:
On Jun 28, 7:42 pm, santosh <santosh....@gmail.comwrote:
>vipps...@gmail.com wrote:
On Jun 28, 2:11 am, Keith Thompson <ks...@mib.orgwrote:
CBFalconer <cbfalco...@yahoo.comwrites:
Flash Gordon wrote:
Kapteyn's Star wrote:
... snip ...
> scanf("%d",&val);
scanf is generally a poor choice of function for user input.
Better to use fgets and then pass the entered line possibly
using sscanf. Whatever you use you should check the value
returned by the input function.
Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.
>[...]
>Alas, this is not true; there's no reliable way to check for
overflow.
>C99 7.19.6.2p10:
> If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object,
the behavior is undefined.
Are you saying that scanf("%d", &intvariable); is _not_ safe even
if the return value of scanf() is properly checked?
Which input would break it?

An input sequence that would cause overflow upon assignment would
break it. In this case undefined behaviour is invoked, which means
that scanf is free to do anything. It might or might not set errno.
That's QoI. A signal might also be raised.
The only way to detect overflow is to either convert manually or
employ the strto* family of functions.
What about this: scanf("%4d", &inttype);
Yes, I think this would be safe from overflow, but it rather restricts
the utility of the function, doesn't it? :-)
Surely that's safe, is it not?
I always thought scanf() could detect/avoid overflow. I start to
dislike scanf and friends.
The scanf family of functions I understand were created in an era when
computers where operated only by trained specialists and garbage or
malformed input was most unlikely. It's still useful for reading
strictly formatted input from trusted sources, but not very robust for
program that might receive input interactively and from anyone. In
practise though, overflow is often not dealt with at all, or only very
rarely.

Jun 28 '08 #33
vi******@gmail.com wrote:
Keith Thompson <ks...@mib.orgwrote:
>CBFalconer <cbfalco...@yahoo.comwrites:
.... snip ...
>>
>>Actually scanf is a quite safe way to input single (emphasize
single) numeric values interactively, as long as you check its
return value.

[...]

Alas, this is not true; there's no reliable way to check for
overflow.

C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object,
the behavior is undefined.

Are you saying that scanf("%d", &intvariable); is _not_ safe
even if the return value of scanf() is properly checked?
Which input would break it?
Yes. Any value larger than INT_MAX or smaller than INT_MIN.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Jun 28 '08 #34
santosh wrote:
vi******@gmail.com wrote:
.... snip ...
>
>Are you saying that scanf("%d", &intvariable); is _not_ safe even
if the return value of scanf() is properly checked?
Which input would break it?

An input sequence that would cause overflow upon assignment would
break it. In this case undefined behaviour is invoked, which means
that scanf is free to do anything. It might or might not set errno.
That's QoI. A signal might also be raised.

The only way to detect overflow is to either convert manually or
employ the strto* family of functions.
Not so. Writing a routine that does what you want is adequate.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Jun 28 '08 #35
santosh <sa*********@gmail.comwrites:
[...]
The scanf family of functions I understand were created in an era when
computers where operated only by trained specialists
Ok.
and garbage or
malformed input was most unlikely.
Oh really?

I think it's more likely that it was before the idea of "undefined
behavior" had been introduced. Programmers knew what happened on
overflow (typically silent wraparound, so entering "65535" when an int
was expected would yield -1). Or at least they knew what happened on
the system they were using, and didn't worry so much about what might
happen on other systems.

There was probably also an attitude that it's the user's
responsibility to provide correct input, not the programmer's
responsibility to handle bad input gracefully.

See also gets().

When the language was standardized, it wasn't considered practical to
define a single behavior for all systems, so it was left undefined.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 28 '08 #36
CBFalconer said:
santosh wrote:
>vi******@gmail.com wrote:
... snip ...
>>
>>Are you saying that scanf("%d", &intvariable); is _not_ safe even
if the return value of scanf() is properly checked?
Which input would break it?

An input sequence that would cause overflow upon assignment would
break it. In this case undefined behaviour is invoked, which means
that scanf is free to do anything. It might or might not set errno.
That's QoI. A signal might also be raised.

The only way to detect overflow is to either convert manually or
employ the strto* family of functions.

Not so. Writing a routine that does what you want is adequate.
That's what he meant by "convert manually".

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 29 '08 #37

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Henri Schomäcker | last post by:
Hi folks, I got a windows com executable which returns a jpg image in a BSTR. Let's say, the var that holds the data is $imgData. With perl, in a cgi script, I may simpy write:...
3
by: Rim | last post by:
Hi, >>> print '%x' % 54 36 >>> print '%b' % 54 Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: unsupported format character 'b' (0x62) at index 1 >>>
4
by: Rusty Shackleford | last post by:
I have a Summer in front of me without any school, and I'd like to add a new format for python print strings that will show any number in a binary representation. For example: >>> '%b' % 3 11...
12
by: neutrino | last post by:
Greetings to the Python gurus, I have a binary file and wish to see the "raw" content of it. So I open it in binary mode, and read one byte at a time to a variable, which will be of the string...
8
by: Lucas | last post by:
I need print a file in binary mode . f = f.open('python.jpg','rb') bytes = f.read() f.close() print(bytes) I can't get any binary code.
14
by: mosi | last post by:
Problem: how to get binary from integer and vice versa? The simplest way I know is: a = 0100 a 64 but: a = 100 (I want binary number) does not work that way.
12
by: waterdriven | last post by:
Hello; I am a newbie. A homework assignment was assigned and I am having trouble getting started. The assignment reads: Write a program to print out the binary value of a 16 bit number.
5
by: dmitrey | last post by:
hi all, could you inform how to print binary number? I.e. something like print '%b' % my_number it would be nice would it print exactly 8 binary digits (0-1, with possible start from 0) ...
0
by: castironpi | last post by:
On May 7, 3:31 pm, Mensanator <mensana...@aol.comwrote: ) for a in range( 10 ) ] ) 00000000 00000001 00000010 00000011 00000100 00000101 00000110
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.