Sunday, July 8, 2007

Write a C progam to convert from decimal to any base (binary, hex, oct etc...).

Here is some really cool C code


#include < stdio.h >

int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}

decimal_to_anybase(int n, int base)
{
int i, m, digits[1000], flag;
i=0;

printf("\n\n[%d] converted to base [%d] : ", n, base);

while(n)
{
m=n%base;
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
n=n/base;
i++;
}

//Eliminate any leading zeroes
for(i--;i >= 0;i--)
{
if(!flag && digits[i]!='0')flag=1;
if(flag)printf("%c",digits[i]);
}
}

37 comments:

Anonymous said...

I could get your code to work.
It seemed to get stuck doing the same thing over, meaning result was the number 9 for each base.

Here is my example fixing yours, but with changes that made more sense to mea and I think make the code more understandable as to what it is doing.

#include stdio.h /*altered tag*/
void decimalToAnyBase(int, int);
main()
{
int num, base;

while (scanf("%d %d",&num, &base) == 2)
{
printf("%d converted to base %d\n",num,base);
decimalToAnyBase(num,base);
putchar('\n');
}

return 0;
}

/* define the decimalToAnyBase() function */
void decimalToAnyBase(int n, int b)
{
int i, m, digits[1000], flag;

i = 0;
m = n % b;

// Keep going if number 'n' is > the base and not zero
if (n >= b)
{
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
printf("digits[%d] = %d.%d\t\tn = %d\n",i,digits[i],m,n);
n = n / b;
i++;
decimalToAnyBase(n,b); /* recursive call */
} else if (n != 0) {
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
printf("digits[%d] = %d.%d\t\tn = %d\n",i,digits[i],m,n);
n = n / b;
i++;
decimalToAnyBase(n,b);
}

Hope this helps...
Mark (medeepthinker)

medeepthinker said...

Hey I think I just managed to sigh up. Cool!

Anonymous said...

Bonjorno, vijayinterviewquestions.blogspot.com!
[url=http://viagraenat.pun.pl/ ]Comprare viagra generico[/url] [url=http://cialisdkee.pun.pl/ ]Compra cialis generico[/url] [url=http://viagraycla.pun.pl/ ]Compra viagra generico[/url] [url=http://cialisonya.pun.pl/ ]Compra cialis generico[/url] [url=http://viagrareta.pun.pl/ ]Acquistare viagra generico[/url] [url=http://cialisybea.pun.pl/ ]Vendita cialis online[/url]

Anonymous said...

How can i remove windows xp from my laptop and reinstall windows Me -the laptops original software?
I suffer with recently bought a familiar laptop that is old. The himself I had bought it from had installed windows xp on it, even though it originally came with windows Me. I be to oust the windows xp because it runs slows on the laptop because it takes up more honour than the windows Me would. Also I want to remove windows xp because it is an forbidden copy. So when I tried to run updates on it, windows would not initiate updates because the windows xp is not genuine. [URL=http://fhmesoa.hostific.com]air brush for finger nails[/URL]
----------------------------------------------------------------------

Answers :

It's best to take one's leave of [URL=http://mpgyvib.instantfreehosting.com/remington-700-bolt-handle-locking-safety.html]remington 700 bolt handle locking safety[/URL] Windows XP and even-handed upgrade your laptop. It's much better. [URL=http://noxynjc.hostific.com/mcafee-superdat.html]mcafee superdat[/URL] Besides, Windows XP is style [URL=http://phckoke.hostific.com/justin-toper.html]justin toper[/URL] healthier then Windows Me. Windows Me is d‚mod‚ and multifarious programs that can come across with XP, can't [URL=http://wjevqea.instantfreehosting.com/55-homes-victorville-ca.html]55 homes victorville ca[/URL] vamoose with Me.
------------------------------
all you have to do is brochure the windows me disk into the cd drive. then reboot your laptop, when the coal-black [URL=http://kiafruu.hostific.com/big-rideau-lake-cottage-properties.html]big rideau lake cottage properties[/URL] shield with all the info comes up and when it asks u to boot from cd [URL=http://leuqaua.hostific.com/tushy-licking-blog.html]tushy licking blog[/URL] chance any indication when it tells you to then inaugurate from there !!! I RECOMEND SINCE ITS AN ILLEAGLE TEXT TO WIPE [URL=http://syaioag.hostific.com/ametrine-mens-ring.html]ametrine mens ring[/URL] MANIFEST THE [URL=http://zxrengh.hostific.com/roatan-resorts.html]roatan resorts[/URL] THOROUGH TIRING DRIVE WHEN IT ASKS YOU WHICH IMPENETRABLE [URL=http://xyeyjqa.hostific.com/chin-strap-adapter.html]chin strap adapter[/URL] GOAD TO POSITION IT ON. THEN SUM ALL THE UNENCUMBERED PAUSE ON THE EMPTY [URL=http://dfizone.hostific.com/tassimo-sweepstakes.html]tassimo sweepstakes[/URL] FLINTY DRIVE ONTO A DIFFERENT COLUMN SETTING, IT WILL-POWER LOOK LIKE C:/ Open or something like that

Anonymous said...

Non-malignant prostatic hyperplasia, commonly known as BPH, is an enlargement of the prostate area. It is more rampant in older men. As men are comely more cultivated about robustness issues, they convert to medical treatment for BPH. Dutas, a generic formation of Avodart([URL=http://jeqpqpv.1freewebspace.com/avodart-and-heart-problems.html]avodart and heart problems[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-diarrhea-sideeffects.html]avodart diarrhea sideeffects[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-prostate-reduction.html]avodart prostate reduction[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-prostate.html]avodart prostate[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-and-insomnia.html]avodart and insomnia[/URL] ), has been proven as an moving treatment of BPH. BPH and its symptoms that adversely upset the grade of lifestyle can be treated successfully nearby Dutas. The essential foretoken evidence of BPH is the frequency of requisite to urinate. This occurs chiefly at vespers all the time but then progresses to the have occasion for to urine again throughout the day. BPH sufferers subsequently circulate a reduction in power in urine stream. Trouble accompanies this reduction. A medical doctor should carry testing to determine if BPH is the grounds of the symptoms. The effectiveness of Dutas is found in the chemical compound Dutasteride. This active ingredient is an alpha-reductase 5 inhibitor which impedes the conversion of testosterone into dihydrotestosterone (DHT). DHT is considered a persuasive technique of testosterone. BPH symptoms vanish promptly the conversion is interrupted. Dutas has been base to be junk in BPH for many sufferers. Prescriptions finasteride and finasteride has been shown to at best curb at one isoform of alpha redictase 5. It has been established that Dutasteride has been proven to hold back two isoforms. Dutas incontestably appears to furnish the pre-eminent treatment close by seeking BPH. Dutas press be charmed as directed with some precautions. Erectile dysfunction and decreased genital libido are the most commonly reported side effects during routine of Dutas. Gynecomastia or enlargement of manly heart network is another accomplishable side effect. Additionally, women who are productive or women inferior to be proper pregnant should not be exposed to Dutas; developing masculine fetuses can be adversely pretentious before these inhibitors. Dutas can be engaged wholly the fell so individual dolour should be exercised in regard to expressive women or women second-rate to ripen into pregnant. Another side effect of Dutas is a favourable one. Some men possess reported hair replenishment while enchanting Dutas. BPH can be treated by discussing medications and feasible side effects with a medical professional. Dutas can give impressive treatment of BPH. A worry-free, potent life is justly quality the effort.
[URL=http://jeqpqpv.1freewebspace.com/avodart-and-lower-psa.html]avodart and lower psa[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-effectiveness-hair-loss.html]avodart effectiveness hair loss[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-for-hair-loss-study.html]avodart for hair loss study[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-psa.html]avodart psa[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-medicine.html]avodart medicine[/URL]

subburajr said...

int convert(unsigned int num, int base)
{
static char buf[33];
char *ptr;
int i = 0,j;

ptr=&buf[sizeof(buf)-1];
*ptr='\0';

do
{
*--ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);

for(j = 0; j <= strlen(ptr); j++){

if( ('0' <= ptr[j]) && ('9' >= ptr[j]))
i = (i<<4)+(ptr[j]-'0');
else if(('a' <= ptr[j]) && ('f' >= ptr[j]))
i = (i<<4) + (ptr[j]-'a') + 0xa;
else if(('A' <= ptr[j]) && ('F' >= ptr[j]))
i = (i<<4)+ (ptr[j]-'A') + 0xa;
}
return i;
}

Anonymous said...

post66, http://www.rc.umd.edu/cstahmer/cogsci/ viagra pro, htmf3, http://www.rc.umd.edu/ order viagra

Anonymous said...

I love vijayinterviewquestions.blogspot.com! Here I always find a lot of helpful information for myself. Thanks you for your work.
Webmaster of http://loveepicentre.com and http://movieszone.eu
Best regards

Anonymous said...

I love dis site. It's indeed very helpful n knowledgeable. Now i'm clear in many of my logics.

Anonymous said...

best place to buy xanax online 4mg xanax and alcohol - caffeine pills xanax

Anonymous said...

clomid clomiphene | how to buy clomid online - can i buy clomid over the counter, clomid twins rate

Anonymous said...

Υоur сurrent artіcle has verified necеssary to mе.
Ӏt’s reаlly hеlpful аnd you're naturally very well-informed of this type. You possess opened up my own face to varying views on this subject matter along with intriguing and solid written content.

My webpage; Klonopin
Also visit my web blog ; Klonopin

Anonymous said...

Hello colleagues, how is all, and what you want to say concerning this post,
in my view its actually remarkable for me.


Feel free to surf to my page tringle à rideaux pour fenetre pvc

Anonymous said...

This desіgn іs steller! You definitely κnow how tо keep a reаdег amused.

Between youг ωit and your videos,
I wаs almost moved to start my own blog (well, almost.
..HaHa!) Great job. I really lovеd whаt уou had tο say, and more than that,
how yοu ρresented it. Too cool!

My web-site: montage porte de garage sectionnelle motorisée

Anonymous said...

Good day! This post could not be written any better!
Reading this post reminds me of my old room mate! He always kept talking about this.

I will forward this page to him. Fairly certain he will have a
good read. Thank you for sharing!

My website ... lame de terrasse en pin

Anonymous said...

I know this web site offers quality based posts and extra
material, is there any other website which offers these data
in quality?

Also visit my weblog :: fenetre pvc couleur bois

Anonymous said...

Hello there! Quick question that's completely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone4. I'm trying to find a template or plugin that might be able to
fix this problem. If you have any suggestions, please share.
Appreciate it!

my web-site ... phenixoption

Anonymous said...

Its like you read my mind! You appear to know a
lot about this, like you wrote the book in it
or something. I think that you can do with some pics
to drive the message home a little bit, but instead of that, this is wonderful blog.
A great read. I'll certainly be back.

Also visit my webpage - prix fenetre pvc double vitrage

Anonymous said...

If some one needs to be updated with hottest technologies
then he must be visit this website and be up to date all
the time.

Also visit my weblog - fenetre pvc devis en ligne

Anonymous said...

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up!
I'll go ahead and bookmark your website to come back later on. All the best

My page carrelage terrasse imitation bois

Anonymous said...

What a material of un-ambiguity and preserveness of valuable know-how on the
topic of unexpected emotions.

Also visit my weblog: porte fenetre en pvc

Anonymous said...

Good blog post. I abѕolutely love this site.
Kеeр it up!

Feel frеe to viѕіt my homеpage;
porte de garage sectionnelle tubauto

Anonymous said...

Very nice post. I just stumbled upon your blog and wished to say
that I've truly enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

My web page tringle rideau fenetre pvc

Anonymous said...

Very nice article, exactly what I wanted to find.



Feel free to surf to my web site; fenetre pvc occasion

Anonymous said...

I don't drop a great deal of responses, but after looking at through a few of the responses on this page "Write a C progam to convert from decimal to any base (binary, hex, oct etc...).". I actually do have a few questions for you if you do not mind. Is it simply me or does it give the impression like some of the comments appear as if they are written by brain dead folks? :-P And, if you are posting at additional places, I would like to follow everything fresh you have to post. Could you make a list of all of all your social community sites like your Facebook page, twitter feed, or linkedin profile?

my website coffre volet roulant

Anonymous said...

You ought to take part in a contest for one of the best blogs on the web.
I'm going to highly recommend this website!

Feel free to visit my webpage; prix d une fenetre pvc double vitrage

Anonymous said...

Thank you for some other great article. The place else may
anybody get that type of information in such an ideal means of writing?
I've a presentation subsequent week, and I'm on the look for such info.


my weblog :: phenix option

Anonymous said...

Way cool! Some very valid points! I appreciate you writing
this article and also the rest of the website is also really good.


My web site - construire sa terrasse en bois

Anonymous said...

My brother recommended I might like this blog. He was entirely right.
This post actually made my day. You can not imagine just how much
time I had spent for this info! Thanks!

my web page; devis fenetre pvc sur mesure

Anonymous said...

Fastidious replies in return of this matter with
genuine arguments and describing the whole thing concerning that.


My page realisation terrasse bois

Anonymous said...

What's Happening i am new to this, I stumbled upon this I've discovered It positively helpful and it has aided me
out loads. I'm hoping to contribute & help other users like its aided me. Good job.

Also visit my web page :: bloque fenetre pvc

Anonymous said...

Ηmm it looks lіkе your sitе ate my first comment (it was super lοng) so I gueѕs I'll just sum it up what I submitted and say, I'm thoгoughly еnjoуing your blоg.
І too am an aspirіng blog wrіter but
I'm still new to everything. Do you have any helpful hints for novice blog writers? I'd genuinely appгеciate it.


Alsо visit mу ωеblog; porte de garage sectionnelle motorisée prix

Anonymous said...

Have you ever thought about including a little
bit more than just your articles? I mean, what
you say is fundamental and all. However imagine if you added some great pictures
or video clips to give your posts more, "pop"!
Your content is excellent but with images and video clips, this blog could undeniably be one of the most beneficial in
its field. Superb blog!

Also visit my weblog poncer un parquet

Anonymous said...

I enjoy what you guys are up too. This sort of clever
work and reporting! Keep up the superb works guys I've incorporated you guys to my own blogroll.

Also visit my website - porte de garage basculante prix

Anonymous said...

Heу wοuld yоu mind lеtting me
knoω whiсh webhοst you're utilizing? I've loaded your blоg in 3 completely dіffeгеnt intегnet broωsers and I muѕt sаy thіs blоg lοads a lot quicker then mοѕt.

Can you гecommend a goοd ωeb hoѕting pгоviԁег at a honest
ρricе? Μany thаnkѕ, І аpprеciate it!


My website porte de garage sectionnelle bois

Anonymous said...

Hello! I κnоw this is kinda off topic hοwevеr I'd figured I'd
asκ. Would you be іntеrеsted in trading links
or maybe guest authοring a blοg article or vіce-versa?

Μy website addresses а lot of the same ѕubjects as youгs and I believе ωе cоuld greatlу bеnеfіt from еach othеr.
If you might be inteгeѕted feеl fгee to ѕend me аn е-mail.
I lоοk fοгward to hearing from you!
Supeгb blog bу the way!

Loοκ into my ωeblog - tarif porte de garage sectionnelle

Anonymous said...

Does your site have a contact page? I'm having a
tough time locating it but, I'd like to send you an email.

I've got some suggestions for your blog you might be interested in hearing.
Either way, great blog and I look forward to seeing it expand over time.


Have a look at my website avis finchmarket