473,396 Members | 1,773 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,396 software developers and data experts.

make a program using C,C++

hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks

Jan 17 '06 #1
52 4047

"mavic" <ma**********@yahoo.com> schreef in bericht
news:11**********************@g14g2000cwa.googlegr oups.com...
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks


And what should happen to the binary/octal/hexadecimal representation?

Arne
Jan 17 '06 #2
there should be an output of these...

Jan 17 '06 #3
here is a program my friend navjot made to convert decimal system
integer to binary.

u can easily change this program to show octal or hexadecimal or any
other system.

#include<stdio.h>
#include<math.h>
main()
{
int i,x,t,answer=0;
int num[15];

clrscr();

printf("Enter the digits of the binary number \n(pressing Enter
between 2 digits and enter 9 when finished entering) : \n");

for(i=0;i<15;i++)
{
scanf("%d",&num[i]);
if( num[i]!=0 && num[i]!=1 )
{break;
}
}

i--;

x=i;

for(t=0;t<=x;t++)
{
/* while(i>=0) */
answer+=(pow(2,t)*num[i]);
i--;
}

printf("%d",answer);

getch();

}
groups.google.com/group/all-at-c

Jan 17 '06 #4
this might b of some help :

#include<stdio.h>
main()
{
int num,i=0,q;
int rem[100];
clrscr();

printf("Enter the number : ");
scanf("%d",&num);
q=num;
while(q>0)
{
rem[i]=q%2;
q=q/2;
i++;
}

while( i>=0 )
{
printf("%d",rem[i-1]);
i--;
}
getch();

}
It only converts integer to binary, integer to other systems can b made
similarly.

Anup Bishnoi

Jan 17 '06 #5

"mavic" <ma**********@yahoo.com> schreef in bericht
news:11**********************@o13g2000cwo.googlegr oups.com...
there should be an output of these...


this should work

#include <stdio.h>

int main()
{
int number = 0, temp = 0, counter = 0;

clrscr();

printf("Give me a number: ");
scanf("%d", &number);
printf("HEXADECIMAL: %04X\n", number);

printf("Octal: ");
while(counter < (sizeof(int)*8 /3))
{
temp = number << (counter*3);
temp >>= (sizeof(int)*8 -3);
printf("%d", temp);
counter++;
}
printf("\nBinary: );
counter = 0;
while(counter < (sizeof(int)*8 ))
{
temp = number << (counter);
temp >>= (sizeof(int)*8 -1);
printf("%d", temp);
counter++;
}

return 0;
}

Arne
Jan 17 '06 #6
Ico
Arne Demmers <ar**********@scarlet.be> wrote:

"mavic" <ma**********@yahoo.com> schreef in bericht
news:11**********************@o13g2000cwo.googlegr oups.com...
there should be an output of these...

[snip homework answer]

Hi Arne,

That's very friendly of you, to do this man's homework; I guess he
really deserves a good grade for that, don't you think so ? His teacher
will be really proud of him, that's for sure. You know, I don't feel
like working today, and I'm just too lazy to learn about the stuff I'm
supposed to be doing, it's all sooooo complicated! If I just tell you
what my job is, can you do it for me ?

Ico

--
:wq
^X^Cy^K^X^C^C^C^C
Jan 17 '06 #7
here is a program my friend navjot made to convert decimal system
integer to binary form.

u can easily change this program to show octal or hexadecimal or any
other system.

#include<stdio.h>
main()
{
int num,i=0,q;
int rem[100];
clrscr();

printf("Enter the number : ");
scanf("%d",&num);
q=num;
while(q>0)
{
rem[i]=q%2;
q=q/2;
i++;
}

while( i>=0 )
{
printf("%d",rem[i-1]);
i--;
}
getch();

}

Anup Bishnoi
groups.google.com/group/all-at-c

Jan 17 '06 #8
Ico
Anup Bishnoi <pi***********@gmail.com> wrote:
this might b of some help : [ snip code ]
It only converts integer to binary, integer to other systems can b made
similarly.


Anup,

Could you please :

- properly quote the messages you are replying to.

- use proper English when posting to this newsgroup. As far as I know,
there are no such words as 'u' and 'b' in English.

- stop making other people's homework. Homework is supposed to give
students a chance to practice the stuff they have learned (or were
supposed to learn); By just giving a way solutions, the man will
graduate his computer course without being able to program properly,
but still he will be assigned to write the fly-by-wire software for
the new Boing plane which you will fly with to your summer holiday
next year. You wouldn't want that plane to crash, would you ?
--
:wq
^X^Cy^K^X^C^C^C^C
Jan 17 '06 #9
Yes I know, normally I don't do this too, I don't like lazy persons, but it
was somewhat too much basic C for not doing it at all, probaly should have
been better to give some kind of link to a C manual where you can find all
this kind basics..

Anyway next time less luck for guys/women like him...

Arne

"Ico" <us****@zevv.nl> schreef in bericht
news:43**********************@dreader32.news.xs4al l.nl...
Arne Demmers <ar**********@scarlet.be> wrote:

"mavic" <ma**********@yahoo.com> schreef in bericht
news:11**********************@o13g2000cwo.googlegr oups.com...
there should be an output of these...

[snip homework answer]

Hi Arne,

That's very friendly of you, to do this man's homework; I guess he
really deserves a good grade for that, don't you think so ? His teacher
will be really proud of him, that's for sure. You know, I don't feel
like working today, and I'm just too lazy to learn about the stuff I'm
supposed to be doing, it's all sooooo complicated! If I just tell you
what my job is, can you do it for me ?

Ico

--
:wq
^X^Cy^K^X^C^C^C^C

Jan 17 '06 #10

"Arne Demmers" <ar**********@scarlet.be> wrote in message
news:YM********************@scarlet.biz...

"mavic" <ma**********@yahoo.com> schreef in bericht
news:11**********************@o13g2000cwo.googlegr oups.com...
there should be an output of these...


this should work

#include <stdio.h>

int main()
{
int number = 0, temp = 0, counter = 0;

clrscr();

printf("Give me a number: ");
scanf("%d", &number);
printf("HEXADECIMAL: %04X\n", number);

printf("Octal: ");
while(counter < (sizeof(int)*8 /3))
{
temp = number << (counter*3);
temp >>= (sizeof(int)*8 -3);
printf("%d", temp);
counter++;
}
printf("\nBinary: );
counter = 0;
while(counter < (sizeof(int)*8 ))
{
temp = number << (counter);
temp >>= (sizeof(int)*8 -1);
printf("%d", temp);
counter++;
}

return 0;
}

Arne


You should not be doing homework, but since this won't compile anyway
perhaps the point is moot.
Jan 17 '06 #11
> Could you please :

- properly quote the messages you are replying to.
hey i clicked the reply link to his msg! u can see who replied whom by
clicking on "view as tree"
- use proper English when posting to this newsgroup. As far as I know,
there are no such words as 'u' and 'b' in English.
i'll take care of that. there was a time when i used to hate people who
wrote like this but eventually it just seemed simpler to write that
way!
- stop making other people's homework. Homework is supposed to give
students a chance to practice the stuff they have learned (or were
supposed to learn); By just giving a way solutions, the man will
graduate his computer course without being able to program properly,
but still he will be assigned to write the fly-by-wire software for
the new Boing plane which you will fly with to your summer holiday
next year. You wouldn't want that plane to crash, would you ?


ok i got the point, so as Arne says "no luck for others!"
ps-was teh quoting ok this time?

Jan 17 '06 #12
> You should not be doing homework, but since this won't compile anyway
perhaps the point is moot.


Now you mention it, it indeed contains some mistakes.... What was I
thinking....
Arne
Jan 17 '06 #13
Ico
Hi Anup,

Anup Bishnoi <pi***********@gmail.com> wrote:
Could you please :

- properly quote the messages you are replying to.


hey i clicked the reply link to his msg! u can see who replied whom by
clicking on "view as tree"


No, it's not that simple. What you see as 'google groups' is actually a
world-wide network of servers (which are *not* a part of the google
network) that are distributing the messages all over the planet. This
network already exists for more then 25 years, and is called usenet. You
can find a proper explanation about usenet and google at the following site :
http://cfaj.freeshell.org/google/
- use proper English when posting to this newsgroup. As far as I know,
there are no such words as 'u' and 'b' in English.


i'll take care of that. there was a time when i used to hate people who
wrote like this but eventually it just seemed simpler to write that
way!


It might be simpler to write, but it is definitely not easier to read.
English is not the native language of a lot of visitors and writers on
this newsgroup, and delibirately using obfuscations like 'u' is only
likely to cause confusion.
- stop making other people's homework. Homework is supposed to give
students a chance to practice the stuff they have learned (or were
supposed to learn); By just giving a way solutions, the man will
graduate his computer course without being able to program properly,
but still he will be assigned to write the fly-by-wire software for
the new Boing plane which you will fly with to your summer holiday
next year. You wouldn't want that plane to crash, would you ?


ok i got the point, so as Arne says "no luck for others!"
ps-was teh quoting ok this time?


Fantastic, thanks a lot :)

--
:wq
^X^Cy^K^X^C^C^C^C
Jan 17 '06 #14
On Tue, 17 Jan 2006, Arne Demmers <ar**********@scarlet.be> wrote:-

<snip>
printf("\nBinary: );
counter = 0;
while(counter < (sizeof(int)*8 ))
{
temp = number << (counter);
temp >>= (sizeof(int)*8 -1);
printf("%d", temp);
counter++;
}


Even though it's looks like this is the solution to a homework question,
is there any reason for not doing it this way:

printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
temp = 1 << (counter);
printf("%d", (number & temp) ? 1 : 0);
}
Regards,
David Bolt

--
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62
Jan 17 '06 #15
David Bolt wrote:

On Tue, 17 Jan 2006, Arne Demmers <ar**********@scarlet.be> wrote:-

<snip>
printf("\nBinary: );
counter = 0;
while(counter < (sizeof(int)*8 ))
{
temp = number << (counter);
temp >>= (sizeof(int)*8 -1);
printf("%d", temp);
counter++;
}


Even though it's looks like this is the solution
to a homework question,
is there any reason for not doing it this way:

printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
temp = 1 << (counter);
printf("%d", (number & temp) ? 1 : 0);
}


What is (1 << (sizeof(int)*8)) supposed to be?

--
pete
Jan 17 '06 #16
mavic wrote:

hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks


/* BEGIN new.c */

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

void itoa_b(int n, char *s);

int main(void)
{
int integer;
char string[CHAR_BIT * sizeof integer];

integer = 12345;
itoa_b(integer, string);
printf("The binary representation of %d, is B %s\n",
integer, string);
sprintf(string, "%o", integer);
printf("The octal representation of %d, is 0%s\n",
integer, string);
sprintf(string, "%x", integer);
printf("The hex representation of %d, is 0x%s\n",
integer, string);
return 0;
}

void itoa_b(int n, char *s)
{
int half, min_offset;
char *p, swap;

min_offset = 0;
if (0 > n) {
if (-INT_MAX > n) {
++n;
++min_offset;
}
n = -n;
*s++ = '-';
}
p = s;
half = n;
do {
half /= 2;
*p++ = (char)(n - 2 * half + '0');
n = half;
} while (half != 0);
*s = (char)(*s + min_offset);
*p-- = '\0';
while (p > s) {
swap = *s;
*s++ = *p;
*p-- = swap;
}
}

/* END new.c */

--
pete
Jan 17 '06 #17
Anup Bishnoi wrote:
Could you please :

- properly quote the messages you are replying to.
hey i clicked the reply link to his msg! u can see who replied whom by
clicking on "view as tree"


So what makes you think anyone else is using the same interface? I know
a blind person who reads Usenet and does *not* use Google. I know
people who use text based news readers where there are *no* buttons to
click on. In my case, I have the news reader (not Google) set to hide
all read messages since it makes it easier for me which means that even
with a tree view (I use a threaded view, effectively the same thing) I
might not be able to see the previous post. Finally, there is absolutely
no guarantee that the message you are replying to has, or ever will,
propagate to all the people who see your message.

Google is just one of a vast number of interfaces to Google, and it is a
comparatively recent one at that.

So please quote properly, and that includes leaving in the lines that
say who said what which you just deleted. Your deleting them means it
would require effort for me to see which of the many sensible people
here you were replying to.

Note, this is not intended to be getting at you, rather it is explaining
the situation. I accept that Google don't make it obvious and, in fact,
make it needlessly hard for you to do the right thing. There is a link
off this page http://cfaj.freeshell.org/google/ to a questionair so that
you can vote for Google to "Default quoting of previous message in
replies" which would make it easier for everyone using Google to do the
right thing. Please go and vote to make life better for all Usenet users.
- use proper English when posting to this newsgroup. As far as I know,
there are no such words as 'u' and 'b' in English.


i'll take care of that.


Then do so please. In this post you have continued to use "u" for you.
there was a time when i used to hate people who
wrote like this but eventually it just seemed simpler to write that
way!
Whether it is easier to write like that is largely irrelevant. Please
understand that it is harder to read especially for people for whom
reading English is not easy or natural, such as Dyslexics and people for
whom English is not their first language. I know we have people in both
groups here. Also please remember, you write the post once but it gets
read many times, so if you spend an extra 30 seconds but save 20 people
5 seconds each it is *still* a net saving.

We generally don't mind real errors cause by English not being someone's
first language. Those are natural and understandable. Although sometimes
such errors are pointed out to help people improve their English.

<snip>
ps-was teh quoting ok this time?


No, you snipped the bit saying who you were replying to. However, it was
a vast improvement. Thank you for making the effort though.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 17 '06 #18
On Tue, 17 Jan 2006, pete <pf*****@mindspring.com> wrote:-
David Bolt wrote:

Even though it's looks like this is the solution
to a homework question,
is there any reason for not doing it this way:

printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
temp = 1 << (counter);
printf("%d", (number & temp) ? 1 : 0);
}


What is (1 << (sizeof(int)*8)) supposed to be?

^^^^^^^^^^^^^
gives the number of bits in an int and left-shifts 1 that number of
times.

I suppose that I should have used:

for(counter=(sizeof(int)*CHAR_BIT);counter>=0;--counter)
^^^^^^^^^
However, I'm guessing that you missed the above, which would mean that
mean you missed that for the first run through the loop:

temp = 1 << (counter);

would be the equivalent of:

temp = 1 << ((sizeof(int)*8)-1)
Regards,
David Bolt

--
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62
Jan 17 '06 #19
David Bolt wrote:
On Tue, 17 Jan 2006, pete <pf*****@mindspring.com> wrote:-
David Bolt wrote:

Even though it's looks like this is the solution
to a homework question,
is there any reason for not doing it this way:

printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
temp = 1 << (counter);
printf("%d", (number & temp) ? 1 : 0);
}


What is (1 << (sizeof(int)*8)) supposed to be?

^^^^^^^^^^^^^
gives the number of bits in an int and left-shifts 1 that number of times.


<snip>

I might be going mad (and people will correct me if I am wrong) but
isn't the following all true?
A numeric constant 1 in the source code as above will be treated as
being of type int

If you left shift 1 by the number of bits in an int you get a number
too big to be represented in an int thus causing an overflow

If you cause an overflow you are invoking undefined behaviour and
*anything* can happen. One likely result in the above being
initialising counter to 0, but stranger things could happen.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 17 '06 #20
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-

<snip>
I might be going mad (and people will correct me if I am wrong) but ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is usenet. You'll be corrected even if when you're not wrong.
isn't the following all true?
A numeric constant 1 in the source code as above will be treated as
being of type int

If you left shift 1 by the number of bits in an int you get a number
too big to be represented in an int thus causing an overflow

If you cause an overflow you are invoking undefined behaviour and
*anything* can happen. One likely result in the above being
initialising counter to 0, but stranger things could happen.


But, if you look again, you'll see that 1 isn't being left-shifted by
the number of bits in an int:

for(
counter=(sizeof(int)*8);
counter>=0;
--counter
)

While counter is initialised as the number of bits in an int, I
specifically used --counter to pre-decrement it before passing through
the loop. In other words, it starts with 1 being left-shifted by one
less than the number of bits in an int.
Regards,
David Bolt

--
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62
Jan 17 '06 #21
David Bolt wrote:
for(
counter=(sizeof(int)*8);
counter>=0;
--counter
)

While counter is initialised as the number of bits in an int, I
specifically used --counter to pre-decrement it before passing through
the loop. In other words, it starts with 1 being left-shifted by one
less than the number of bits in an int.


That's not how a for loop works.
Predecrement or postdecrement,
makes no difference in that case.

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
int x;

for (x = 1; x > 0; --x) {
printf("%d\n", x);
}
for (x = 1; x > 0; x--) {
printf("%d\n", x);
}
return 0;
}

/* END new.c */
--
pete
Jan 17 '06 #22
On Tue, 17 Jan 2006, pete <pf*****@mindspring.com> wrote:-
David Bolt wrote:
for(
counter=(sizeof(int)*8);
counter>=0;
--counter
)

While counter is initialised as the number of bits in an int, I
specifically used --counter to pre-decrement it before passing through
the loop. In other words, it starts with 1 being left-shifted by one
less than the number of bits in an int.


That's not how a for loop works.
Predecrement or postdecrement,
makes no difference in that case.


<Snippety of example showing my misconception>

So, after showing off my lack of knowledge, it looks like I've finally
managed to learn something new today. I'd always thought that both a
pre-decrement and pre-increment meant that either the decrement, or
increment, took place before each run through the loop, not afterwards.

In other words, what I should have used is:

for(counter=(sizeof(int)*CHAR_BIT)-1;counter>=0;counter--)
Regards,
David Bolt

--
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62
Jan 17 '06 #23
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Google is just one of a vast number of interfaces to Google, and it is
a comparatively recent one at that.
I think you mean "Google is just one of a vast number of interfaces to
Usenet".

[...]
Whether it is easier to write like that is largely irrelevant. Please
understand that it is harder to read especially for people for whom
reading English is not easy or natural, such as Dyslexics and people
for whom English is not their first language. I know we have people in
both groups here. Also please remember, you write the post once but it
gets read many times, so if you spend an extra 30 seconds but save 20
people 5 seconds each it is *still* a net saving.


It's no fun for those of us who *do* have English as our first
language.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 17 '06 #24
David Bolt wrote:
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-

<snip>
I might be going mad (and people will correct me if I am wrong) but

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is usenet. You'll be corrected even if when you're not wrong.


True, as you proceed to demonstrate :-)
isn't the following all true?
A numeric constant 1 in the source code as above will be treated as
being of type int

If you left shift 1 by the number of bits in an int you get a number
too big to be represented in an int thus causing an overflow

If you cause an overflow you are invoking undefined behaviour and
*anything* can happen. One likely result in the above being
initialising counter to 0, but stranger things could happen.


But, if you look again, you'll see that 1 isn't being left-shifted by
the number of bits in an int:

for(
counter=(sizeof(int)*8);
counter>=0;
--counter
)

While counter is initialised as the number of bits in an int, I
specifically used --counter to pre-decrement it before passing through
the loop. In other words, it starts with 1 being left-shifted by one
less than the number of bits in an int.


The code snipped in full, with added commentary by me was
printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
/* First time though counter will be (sizeof(int)*8) since the --counter
expression is not executed until *after* the first execution of the loop */
temp = 1 << (counter);

/* So the above statement invokes undefined behaviour */

printf("%d", (number & temp) ? 1 : 0);
}

<aside>
I seem to remember a recent thread here about the merits of pre/post
increment when used like this and someone suggesting the pre-increment
could be miss-interpreted in exactly the way David Bolt has just done.
David has just proved that hypothesis, although I would personally use
that as an argument for David to learn more rather than to avoid the
pre-increment. I prefer the post increment, but as a matter of style
rather than belief that it is in some manner better.
</aside>

By the way, even if you "correct" it to:
printf("\nBinary: ");
for(counter=(sizeof(int)*8)-1;counter>=0;--counter)
{
temp = 1 << (counter);
printf("%d", (number & temp) ? 1 : 0);
}
You can still invoke undefined behaviour. To quote from N1124 section
6.5.7 para 4:
| The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated
| bits are filled with zeros. If E1 has an unsigned type, the value of
| the result is E1 * 2**E2, reduced modulo one more than the maximum
| value representable in the result type. If E1 has a signed type and
| nonnegative value, and E1 × 2**E2 is representable in the result type,
| then that is the resulting value; otherwise, the behavior is
| undefined.

I've used ** to represent "raising to the power" since superscript is
not easy to do.

Read the last sentence and you will see that trying to shift a 1 in to
the sign bit of a signed number (and 1 is a signed int) is explicitly
undefined behaviour.

Generally you should make sure you are using unsigned types when using
bit operators to avoid this kind of trap, and that includes specifying
constants as unsigned.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 17 '06 #25
Keith Thompson wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Google is just one of a vast number of interfaces to Google, and it is
a comparatively recent one at that.
I think you mean "Google is just one of a vast number of interfaces to
Usenet".


You, you are quite correct. Can I use dyslexia as an excuse for using
the wrong word?
[...]
Whether it is easier to write like that is largely irrelevant. Please
understand that it is harder to read especially for people for whom
reading English is not easy or natural, such as Dyslexics and people
for whom English is not their first language. I know we have people in
both groups here. Also please remember, you write the post once but it
gets read many times, so if you spend an extra 30 seconds but save 20
people 5 seconds each it is *still* a net saving.


It's no fun for those of us who *do* have English as our first
language.


Agreed. I suspect it is worse for non-native English speakers, and I
know it makes it far harder for me as a dyslexic.

Thank dog for split chickens.
--
Flash Gordon
Dyslexic programmer,
At least the compiler ensures I spell variable names consistently wrong.
Jan 17 '06 #26
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-
David Bolt wrote:
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-
<snip>
I might be going mad (and people will correct me if I am wrong) but ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is usenet. You'll be corrected even if when you're not wrong.


True, as you proceed to demonstrate :-)


True :-(

<snip>
The code snipped in full, with added commentary by me was
printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
/* First time though counter will be (sizeof(int)*8) since the --
counter expression is not executed until *after* the first execution of
the loop */
And that was my mistake. My (lack of) understanding was that the pre-
meant that the increment/decrement was performed before going through
the loop, not afterwards. Now I know I was wrong, and so publicly wrong
as well, it's fairly certain that I won't be repeating that error again.
temp = 1 << (counter);

/* So the above statement invokes undefined behaviour */

printf("%d", (number & temp) ? 1 : 0);
At least I got this bit (almost) right. Having thought about it, and I'm
probably going to see if I can fit a second foot in my mouth at the same
time, I think it would be better if temp was had an unsigned int type,
and after a couple of other tweaks, this code should be okay:

/* number.c */

#include <stdio.h>

int main()
{
int number = 0;
unsigned int temp = 0;
int counter;

printf("Give me a number: ");
scanf("%d", &number);
/*
ought to be checking here on the returned value just in case of
errors/overflows
*/

for(counter=(sizeof(int)*8)-1;counter>=0;counter--)
{
temp = 1UL << counter;
printf("%d", ((unsigned int)number & temp) ? 1 : 0);
}

printf("\n");

return 0;
}

/* number.c */

Now, knowing my luck, there's probably still something wrong. However,
GCC doesn't throw any warnings at me when it compiles, and it does give
the correct output for multiple test values.
}

<aside>
I seem to remember a recent thread here about the merits of pre/post
increment when used like this and someone suggesting the pre-increment
could be miss-interpreted in exactly the way David Bolt has just done.
At least I can still manage to be a good example of how a little
knowledge can be a dangerous thing.
David has just proved that hypothesis, although I would personally use
that as an argument for David to learn more rather than to avoid the
pre-increment.
Learning more does appear to be among the things I've been doing today.
I prefer the post increment, but as a matter of style rather than
belief that it is in some manner better.
After learning that in a for() post- and pre- apparently do the same
thing, it doesn't appear to matter which is used. Personally, I also use
post increments/decrements, but in this case was tripped up by my
misunderstanding.

<Snippety>
Read the last sentence and you will see that trying to shift a 1 in to
the sign bit of a signed number (and 1 is a signed int) is explicitly
undefined behaviour.

Generally you should make sure you are using unsigned types when using
bit operators to avoid this kind of trap, and that includes specifying
constants as unsigned.


And there's another thing I've learnt today. All I have to do now is
remember to change my socks before I go sticking my feet in my mouth
again.
Regards,
David Bolt

--
Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/
AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11
AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02
AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62
Jan 17 '06 #27
David Bolt wrote:

On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-
David Bolt wrote:
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-
<snip>
The code snipped in full, with added commentary by me was
printf("\nBinary: ");
for(counter=(sizeof(int)*8);counter>=0;--counter)
{
/* First time though counter will be (sizeof(int)*8) since the --
counter expression is not executed until *after*
the first execution of the loop */


And that was my mistake. My (lack of) understanding was that the pre-
meant that the increment/decrement was performed before going through
the loop, not afterwards. Now I know I was wrong,
and so publicly wrong
as well, it's fairly certain that I won't be repeating
that error again.
temp = 1 << (counter);

/* So the above statement invokes undefined behaviour */

printf("%d", (number & temp) ? 1 : 0);


At least I got this bit (almost) right. Having thought about it,
and I'm
probably going to see if I can fit a second foot
in my mouth at the same
time, I think it would be better if temp was had an unsigned int type,
and after a couple of other tweaks, this code should be okay:

/* number.c */

#include <stdio.h>

int main()
{
int number = 0;
unsigned int temp = 0;
int counter;

printf("Give me a number: ");
scanf("%d", &number);
/*
ought to be checking here on the returned value just in case of
errors/overflows
*/

for(counter=(sizeof(int)*8)-1;counter>=0;counter--)
{
temp = 1UL << counter;
printf("%d", ((unsigned int)number & temp) ? 1 : 0);
}

printf("\n");

return 0;
}

/* number.c */

Now, knowing my luck, there's probably still something wrong. However,
GCC doesn't throw any warnings at me when it compiles,
and it does give
the correct output for multiple test values.


The (unsigned int) cast doesn't do anything,
because the & operator with the other unsigned operand,
already converts number to type unsigned.
number should probably be unsigned to begin with.
Bitwise operations on negative values are tricky.

CHAR_BIT is preferable to 8, for the number of bits in a byte.

There's also the matter of padding bits.
C99 allows that there may be unused bits in a byte,
that is to say that an int with a 16 bit range,
could be an object that has more than 16 bits.

For an unsigned integer type,
an unsigned expression that has only the most significant bit set
could be: (((unsigned)-1 >> 1) + 1)

--
pete
Jan 17 '06 #28
On Tue, 17 Jan 2006 19:09:47 GMT, in comp.lang.c , Keith Thompson
<ks***@mib.org> wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Google is just one of a vast number of interfaces to Google, and it is
a comparatively recent one at that.


I think you mean "Google is just one of a vast number of interfaces to
Usenet".


I think the first version was better though... after all, Google is
widely considered to be so far up its own a&%^$NO CARRIER

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 17 '06 #29

"mavic" <ma**********@yahoo.com> wrote
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks

Any integer?

Including 10^(10^10) ?
Jan 17 '06 #30
Anup Bishnoi said:
here is a program my friend navjot made to convert decimal system
integer to binary.

u can easily change this program to show octal or hexadecimal or any
other system.

#include<stdio.h>
#include<math.h>
main()
{
int i,x,t,answer=0;
int num[15];

clrscr();
Hmmm. I don't see the point of that.

printf("Enter the digits of the binary number \n(pressing Enter
between 2 digits and enter 9 when finished entering) : \n");

for(i=0;i<15;i++)
{
scanf("%d",&num[i]);


Forgive me, but I don't quite see how you are protecting against your user
typing ONE ONE ONE ZERO ZERO ONE ONE ONE ZERO ONE as input.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 17 '06 #31
"Malcolm" <re*******@btinternet.com> writes:
"mavic" <ma**********@yahoo.com> wrote
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks

Any integer?

Including 10^(10^10) ?


Sure, that's just 10.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 17 '06 #32
David Bolt wrote:
.... snip ...
While counter is initialised as the number of bits in an int, I
specifically used --counter to pre-decrement it before passing
through the loop. In other words, it starts with 1 being
left-shifted by one less than the number of bits in an int.


Which shifts it into the sign bit and creates an overflow and
undefined behaviour. Use unsigned ints for that purpose.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 17 '06 #33
David Bolt wrote:
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-
David Bolt wrote:
On Tue, 17 Jan 2006, Flash Gordon <sp**@flash-gordon.me.uk> wrote:-

<snip>
At least I got this bit (almost) right. Having thought about it, and I'm
probably going to see if I can fit a second foot in my mouth at the same
time,
Indubitably ;-)
I think it would be better if temp was had an unsigned int type,
Definite improvement, since the conversion of unsigned int to signed int
has a problem if the value is too large to fit in the signed int. so
you've side stepped that one nicely :-)
and after a couple of other tweaks, this code should be okay:

/* number.c */

#include <stdio.h>

int main()
{
int number = 0;
unsigned int temp = 0;
int counter;

printf("Give me a number: ");
scanf("%d", &number);
/*
ought to be checking here on the returned value just in case of
errors/overflows
*/

for(counter=(sizeof(int)*8)-1;counter>=0;counter--)
{
temp = 1UL << counter;
printf("%d", ((unsigned int)number & temp) ? 1 : 0);
}

printf("\n");

return 0;
}

/* number.c */

Now, knowing my luck, there's probably still something wrong. However,
GCC doesn't throw any warnings at me when it compiles, and it does give
the correct output for multiple test values.
Well, there is just one little thing that I can see...
When number is converted to unsigned and number is negative, the
conversion will be done as if UINT_MAX to the value. On a 2's complement
machine (i.e. almost all machines these days) this will just reinterpret
the bits as unsigned. However, on a 1's complement or sign & magnitude
system (which the C standard still allows) it will change the bit
pattern. So, basically, your routine always prints the bit pattern of
the 2's complement representation of the number even if that is not what
the implementation uses.

Personally, for all of my real work (as opposed to picking nits here) I
would not worry about it.

<snip>
At least I can still manage to be a good example of how a little
knowledge can be a dangerous thing.
Don't worry about it. We all make errors here.

<snip>
Learning more does appear to be among the things I've been doing today.


With that attitude, I think you will do well in this group. So I'll let
you in to a trade secret...

You can legally download copies of the drafts of the various version of
the C standard for free. This page has the appropriate links
http://clc-wiki.net/wiki/Basics_Of_The_C_Standard
OK, so it's not really a secret. However, it is reference material you
might find useful.
I prefer the post increment, but as a matter of style rather than
belief that it is in some manner better.


After learning that in a for() post- and pre- apparently do the same
thing, it doesn't appear to matter which is used.


It does matter if you use the value of the expression, i.e. these two
are different:
for (i=0; i<10; j=i++) {
/* j uninitialised fist time round then 1 less than i
on subsequent iterations */
}

for (i=0; i<10; j=++i) {
/* j uninitialised fist time round then the same as i
on subsequent iterations */
}

<snip>
Read the last sentence and you will see that trying to shift a 1 in to
the sign bit of a signed number (and 1 is a signed int) is explicitly
undefined behaviour.

Generally you should make sure you are using unsigned types when using
bit operators to avoid this kind of trap, and that includes specifying
constants as unsigned.


And there's another thing I've learnt today. All I have to do now is
remember to change my socks before I go sticking my feet in my mouth
again.


This is good. Making honest errors on this group is fine, accepting
corrections is and learning from them is excellent.

Just don't take my word as gospel until you've either verified it or at
least seen that no one else is pointing out that I've got it wrong.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 18 '06 #34
Keith Thompson wrote:
"Malcolm" <re*******@btinternet.com> writes:
"mavic" <ma**********@yahoo.com> wrote
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks
Any integer? Including 10^(10^10) ?
Sure, that's just 10.


It certainly could be, since the OP didn't specify what base the
input should be in, and you didn't specify what base the number
you gave was in.

Which brings up a point: should the OP's program accept numbers
in decimal only? What about negative numbers?

- Logan
Jan 18 '06 #35
Logan Shaw <ls**********@austin.rr.com> writes:
Keith Thompson wrote:
"Malcolm" <re*******@btinternet.com> writes:
"mavic" <ma**********@yahoo.com> wrote
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks Any integer? Including 10^(10^10) ?
Sure, that's just 10.


It certainly could be, since the OP didn't specify what base the
input should be in, and you didn't specify what base the number
you gave was in.


I assumed 10 was a decimal literal and "^" was the standard bitwise
xor operator. (Yes, I was being deliberately silly.)
Which brings up a point: should the OP's program accept numbers
in decimal only? What about negative numbers?


That needs to be part of the specification.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 18 '06 #36
mavic wrote:
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks


Here is my version (for the general case):

#include <assert.h>

void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num, power = 1, k = 0, digit;

assert((base >= 2) && (base < 10 + 'Z' - 'A'));
while (rem / (power * base) > 0) { power *= base; }
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}
August

--
I am the "ILOVEGNU" signature virus. Just copy me to your
signature. This email was infected under the terms of the GNU
General Public License.
Jan 18 '06 #37
August Karlstrom <fu********@comhem.se> writes:
mavic wrote:
hi to everybody,i need help for my project....how to make a program
that accept any integer and convert it binary,octal and hexadecimal.pls
help me...thanks


Here is my version (for the general case):

#include <assert.h>

void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num, power = 1, k = 0, digit;

assert((base >= 2) && (base < 10 + 'Z' - 'A'));
while (rem / (power * base) > 0) { power *= base; }
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}


I see at least two significant flaws. If they were unintentional,
I'll point them out; if they're deliberate (because it's probably a
homework problem), they're likely to get past the instructor.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 18 '06 #38
pete wrote:
...
void itoa_b(int n, char *s)
{
int half, min_offset;
char *p, swap;

min_offset = 0;
if (0 > n) {
if (-INT_MAX > n) {
++n;
++min_offset;
}
On my system, -2147483648 (INT_MIN) produced
-1111111111111111111111111111112.
n = -n;
*s++ = '-';
}
p = s;
half = n;
do {
half /= 2;
*p++ = (char)(n - 2 * half + '0');
n = half;
} while (half != 0);
*s = (char)(*s + min_offset);
*p-- = '\0';
while (p > s) {
swap = *s;
*s++ = *p;
*p-- = swap;
}
}


Alternatively...

void itoa_b(int n, char *s)
{
unsigned m = 0;
unsigned u = n;

if (n == 0)
m = 1;
else if (n < 0)
{
*s++ = '-';
u = -u;
if (u == 0) /* INT_MAX == UINT_MAX && n == INT_MIN */
{ *s++ = '1'; m = -1u/2+1; }
}

if (!m)
for (m = -1u/2+1; m && !(u & m); m >>= 1)
;

for (; m; m >>= 1)
*s++ = '0' + !!(u & m);

*s = 0;
}

--
Peter

Jan 18 '06 #39
Keith Thompson wrote:
Logan Shaw <ls**********@austin.rr.com> writes:
Keith Thompson wrote:
"Malcolm" <re*******@btinternet.com> writes: Any integer?
Including 10^(10^10) ? Sure, that's just 10.
It certainly could be, since the OP didn't specify what base the
input should be in, and you didn't specify what base the number
you gave was in.
I assumed 10 was a decimal literal and "^" was the standard bitwise
xor operator. (Yes, I was being deliberately silly.)
Yeah, it certainly could be. But it also works if 10^(10^10) is
interpreted as an expression with some binary numbers raised to
the power of some other numbers, because the value of that expression
would be (in hexadecimal) 10.
Which brings up a point: should the OP's program accept numbers
in decimal only? What about negative numbers?

That needs to be part of the specification.


Exactly.

- Logan
Jan 18 '06 #40
Peter Nilsson wrote:

pete wrote:
...
void itoa_b(int n, char *s)
{
int half, min_offset;
char *p, swap;

min_offset = 0;
if (0 > n) {
if (-INT_MAX > n) {
++n;
++min_offset;
}


On my system, -2147483648 (INT_MIN) produced
-1111111111111111111111111111112.


Good catch!
n = -n;
*s++ = '-';
}
p = s;
half = n;
do {
half /= 2;
*p++ = (char)(n - 2 * half + '0');
n = half;
} while (half != 0);
*s = (char)(*s + min_offset);
*p-- = '\0';
while (p > s) {
swap = *s;
*s++ = *p;
*p-- = swap;
}
}


Alternatively...

void itoa_b(int n, char *s)
{
unsigned m = 0;
unsigned u = n;

if (n == 0)
m = 1;
else if (n < 0)
{
*s++ = '-';
u = -u;
if (u == 0) /* INT_MAX == UINT_MAX && n == INT_MIN */
{ *s++ = '1'; m = -1u/2+1; }
}

if (!m)
for (m = -1u/2+1; m && !(u & m); m >>= 1)
;

for (; m; m >>= 1)
*s++ = '0' + !!(u & m);

*s = 0;
}


That works for me.

--
pete
Jan 18 '06 #41
Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
Here is my version (for the general case):

#include <assert.h>

void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num, power = 1, k = 0, digit;

assert((base >= 2) && (base < 10 + 'Z' - 'A'));
while (rem / (power * base) > 0) { power *= base; }
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}

I see at least two significant flaws.


You are quite right.

The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base 36.
Of course I assume ASCII correspondence between characters and ordinals.

The following version is more likely to be correct:

#include <assert.h>

#define BASE_MAX ('9' - '0' + 1 + 'Z' - 'A' + 1)

void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num / base, power = 1, k = 0, digit;

assert((base >= 2) && (base <= BASE_MAX));
while (rem > 0) { /* loop invariant: power * base <= num */
power *= base;
rem /= base;
}
rem = num;
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}
If they were unintentional, I'll point them out; if they're deliberate (because it's probably a homework problem), they're likely to

get past the instructor.

Good or bad depending on how you see it ;-)
August

--
I am the "ILOVEGNU" signature virus. Just copy me to your
signature. This email was infected under the terms of the GNU
General Public License.
Jan 18 '06 #42

Richard Heathfield wrote:
Forgive me, but I don't quite see how you are protecting against your user
typing ONE ONE ONE ZERO ZERO ONE ONE ONE ZERO ONE as input.


actually it requires you to enter some other (other than 0 and 1)
number after you have finished entering the binary number.

input like : ONE ZERO ZERO ONE ONE NINE

this would give output 19

Jan 18 '06 #43
August Karlstrom <fu********@comhem.se> writes:
[...]
The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base
36. Of course I assume ASCII correspondence between characters and
ordinals.


Why do you assume ASCII?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 18 '06 #44
Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
[...]
The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base
36. Of course I assume ASCII correspondence between characters and
ordinals.

Why do you assume ASCII?


I was thinking that there may be some unheard of encoding in which '0'
to '9' and 'A' to 'Z' respectively are not represented by consecutive
integers.
August

--
I am the "ILOVEGNU" signature virus. Just copy me to your
signature. This email was infected under the terms of the GNU
General Public License.
Jan 18 '06 #45
August Karlstrom wrote:

Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
[...]
The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base
36. Of course I assume ASCII correspondence between characters and
ordinals.

Why do you assume ASCII?


I was thinking that there may be some unheard of encoding in which '0'
to '9' and 'A' to 'Z' respectively are not represented by consecutive
integers.


'0' to '9' are always consecutive values.

'A' through 'Z'
can be any positive value less than or equal to CHAR_MAX.

One of the non ascii character sets is called EBDIC or EBCDIC.

http://www.natural-innovations.com/c...ciiebcdic.html

--
pete
Jan 18 '06 #46
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

August Karlstrom wrote:
Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
[...]
The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base
36. Of course I assume ASCII correspondence between characters and
ordinals.
Why do you assume ASCII?


I was thinking that there may be some unheard of encoding in which '0'
to '9' and 'A' to 'Z'


FWIW, all variants of EBCDIC leave big gaps in 'A' to 'Z', interposing
other characters in those gaps. So, for EBCDIC, 'A' to 'Z' means
something like
A, B, C, D, R, F, G, H, I, <bad value>, <bad value>, ... }, J, K, ...
respectively are not represented by consecutive
integers.
August

- --

Lew Pitcher, IT Specialist, Enterprise Data Systems
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFDznFeagVFX4UWr64RAs/zAKCNK6YK/nmQp2MqNQygFOXMifnt8wCePjgL
7O+htqrlQNzGOfN7SDCX//I=
=FSDo
-----END PGP SIGNATURE-----
Jan 18 '06 #47
August Karlstrom <fu********@comhem.se> writes:
Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
[...]
The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base
36. Of course I assume ASCII correspondence between characters and
ordinals.

Why do you assume ASCII?


I was thinking that there may be some unheard of encoding in which '0'
to '9' and 'A' to 'Z' respectively are not represented by consecutive
integers.


Right, that was my point. The C standard guarantees that '0' .. '9'
are consecutive, but it makes no such guarantee about 'A' .. 'Z' (or
about any other letters).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 18 '06 #48
August Karlstrom wrote:
Keith Thompson wrote:
August Karlstrom <fu********@comhem.se> writes:
Here is my version (for the general case):

#include <assert.h>

void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num, power = 1, k = 0, digit;

assert((base >= 2) && (base < 10 + 'Z' - 'A'));
while (rem / (power * base) > 0) { power *= base; }
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}
I see at least two significant flaws.


You are quite right.

The calculations in the implementation above will easily overflow and
`base < 10 + 'Z' - 'A'' should really be `base <= '9' - '0' + 1 +
'Z' - 'A'' (to be explicit), so my implementation works up to base 36.


You are still off by one in your base check, assuming ASCII. If EBCDIC,
it's worse. I am ignoring the superfluous trailing apostrophe for now.
Of course I assume ASCII correspondence between characters and ordinals.

The following version is more likely to be correct:

#include <assert.h>

#define BASE_MAX ('9' - '0' + 1 + 'Z' - 'A' + 1)
I see you fixed it here.
void get_num_in_base(char *res, unsigned num, unsigned base)
{
unsigned rem = num / base, power = 1, k = 0, digit;

assert((base >= 2) && (base <= BASE_MAX));
while (rem > 0) { /* loop invariant: power * base <= num */
Assume you start with num=1. The invariant is initially wrong.
power *= base;
rem /= base;
}
rem = num;
while (power > 0) {
digit = rem / power;
res[k] = ((digit < 10)? '0': 'A' - 10) + digit;
rem -= digit * power;
power /= base;
k++;
}
res[k] = '\0';
}


The code will now always generate a leading 0, which I would consider an
error. If you attempt to convert UINT_MAX-1, you will get a divide by 0.

Try again.

--
Thad
Jan 19 '06 #49
Anup Bishnoi said:

Richard Heathfield wrote:
Forgive me, but I don't quite see how you are protecting against your
user typing ONE ONE ONE ZERO ZERO ONE ONE ONE ZERO ONE as input.


actually it requires you to enter some other (other than 0 and 1)
number after you have finished entering the binary number.

input like : ONE ZERO ZERO ONE ONE NINE

this would give output 19


....but didn't. Care to think again?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 19 '06 #50

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

Similar topics

13
by: takashi | last post by:
Hi, I have a question. I am learning about how to use c++ language. I have attempted to make my own programs, using the knowledge that I have, but sometimes when I get stuck on writing a code, it...
11
by: bart | last post by:
Hello, I'm so sorry, but i don't understand the concept of the .net environment yet. I made a simple program that retrieves the hostname and ipaddress of the local computer. But when i give...
17
by: UJ | last post by:
Is there any way for a windows service to start a windows program ? I have a service that will need to restart a windows app if it needs to. TIA - Jeff.
6
by: scottyman | last post by:
I can't make this script work properly. I've gone as far as I can with it and the rest is out of my ability. I can do some html editing but I'm lost in the Java world. The script at the bottom of...
7
by: Hal Vaughan | last post by:
I have a problem with port forwarding and I have been working on it for over 2 weeks with no luck. I have found C programs that almost work and Java programs that almost work, but nothing that...
8
by: Seeker | last post by:
Hello, In using Solaris Pro Compiler to compile Pro*C code. I am getting this error: make: Fatal error in reader: parser_proc_online.mk, line 26: Badly formed macro assignment Based on other...
19
by: zzw8206262001 | last post by:
Hi,I find a way to make javescript more like c++ or pyhon There is the sample code: function Father(self) //every contructor may have "self" argument { self=self?self:this; ...
48
by: istillshine | last post by:
When I used gprof to see which function consumed most running time, I identified the following one. sz was less than 5000 on average, but foo had been called about 1,000,000 times. I have tried...
42
by: lorlarz | last post by:
Contrary to what one authority in the JavaScript field says: JavaScript does make errors when dealing with just with integers. This authority (Douglas Crockford.) says: "integer arithmetic in...
82
by: Bill David | last post by:
SUBJECT: How to make this program more efficient? In my program, a thread will check update from server periodically and generate a stl::map for other part of this program to read data from....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.