Converting a decimal to a binary in C (output missing digits) - arrays

Why is it returning 7 digits instead of 8 digits once binary array's length is 8 (meaning 8 bits)?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int number = get_int("Number: ");
char binary[8]; // 8 bits in a byte
for (int i = 0; number != 0 ; i++)
{
if (number % 2 == 0)
{
binary[i] = '0';
}
else
{
binary[i] = '1';
}
number /= 2;
}
printf("%s\n", binary);
}
I'm getting
Number: 72
Binary: 0001001
I know it's reversed from the correct answer for this decimal, just want to correct the missing digit first.

For your program, I only had to make one small correction:
https://ideone.com/87v18W
int main(void)
{
int number = 145;
char binary[8+1] = {}; // 8 bits in a byte, + 1 for string-terminator
// If you're going to print it out as a string, you have to make sure there is space for a nil-terminator ('\0') at the end of the string.
// Hence the +1 for space, and the ={}; to set the whole thing to 0 before filling in the bits.
for (int i = 0; number != 0 ; i++)
{
if (number % 2 == 0)
{
binary[i] = '0';
}
else
{
binary[i] = '1';
}
number /= 2;
}
printf("%s\n", binary);
}
When I run this program, with input of 145, I get
Output
10001001
Here's how I do ints to binary, with a . separator every 8 bits:
#include <stdio.h>
#include <limits.h>
#include <stdint.h>
int main(void) {
uint32_t num = 93935;
for(int i=(sizeof(uint32_t)*CHAR_BIT)-1; i>=0; --i)
{
printf("%c%s", "01"[!!(num & (1<<i))], i%8?"":i?".":"");
}
return 0;
}
Example Output:
Success #stdin #stdout 0s 5404KB
00000000.00000001.01101110.11101111

Related

Digital Root in c

So you have to do:
11 = 1+1 = 2
3578 = 3+5+7+8 = 23 = 2+3 = 5
But the problem is that the number can be very large(consist of 10,000 digits)
#include <stdio.h>
#include <ctype.h>
int main(){
char buffer[100000];
scanf("%99999s", buffer);
unsigned long long int result = 0;
for( unsigned idx = 0; isdigit(buffer[idx]); idx++ ){
result = (int)buffer[idx] + result - '0';
}
int result2 = 0;
int digit = 0;
while ( result > 0 ){
digit = result % 10;
result2 += digit;
result = result / 10;
if( result <= 0 && result2 > 9){
result = result2;
result2 = 0;
continue;
}
}
printf("RESULT : %d\n",result2);
}
Input :
751681014401040450622780075254045270442210812770460775451184384531483702082226416361544531414410171607350014850333878358743220376871078174403200044662362218387877088216176613360252864405743551700372186186575780774423365770110772762276064451888336156654128153746808000717416854455788814078402738512314518407278677742343615032578760156411281210127537668157717015666162165516525027107402068668123177553108546580071328732081607873181528418805507115473871188671175418353685287375851146862706642660460660640361450625482328733578704685372147576117063756404450651264407575360484374363385487210664552841370274325526483461688624004361174850045865227812614165458631837856673343826214104801877607136035412561647757156215008153430481053606347145474412241557035145221136028312706780031881775353428185131338124663027888077214386322084144228202118607125173881566084750330384756507240153360252125102231317116187460551751644005660558858277077053174524651718580360376435305240031868065863876643181746460523888528353776530743505576145346723312843737184587288444786213277214628281832785420546274087146761566864614047504688123772643616870148637036486545882717162028017172706874088300344834424111884355042605060726257071061472334164583725618637172662277276238285574537252303708512187713753768210883717883214177506821154744051238430026270855363428730658126314153612053400077268874042185164222701426867051627554247573272557376740151571806220637182717476783435840540164172408587171868366825071315532702431761021552623061343345432712675051436011076617066231844451104348332548221106105114023473728208461760881801028437428634770630222621088305700346277351457830386857805275647013556147441362065165825384420633364237016227253566137375754313815436352300840071213800623627143462831576581300375511873047806550427070820275112032855056137212406102042344837643783510606621032343518643584052038422148828271478733221816003564556283801864300304433172707473414552811044246731560263787181360375220856023782825227102624663780175705186245881553055783106085313045005862533446468632134156855843085604348382611533515253722765723825136013746254432618268575605574880777370574873416807208456637441333184132067035322454017072312638668737073738377347585458061613007130848158715255752218380205816085742220815543528204180550315407345040343465616657842185850163106537650131781684036344622188084870842413154385436162802282440416080100438843655544106712445324162727681876878667304463852468413048081441201022820146183282812314331114888177386525521660163781083757743180378743438208686328556162024886323326120153038720833558641743826880113166153240558815120076524147752615042565452038541813882006275635438131506100314186187302343688270237767287844414752004085217272576403406754126201126712336183622843312501717384047822064857500303244180435065521612467421283018275707044616755208768040404760152323626173084386326286466747754211888301380460737572061342836367388845034654501045572058038063025335007602521812172166057474442286006578638145768783310135200717742254225860404885176720441047442166271805032286547386064076324568835101011406416753172855727057633455343825574000185777457428046681783622861257212832770071867083635215251007450841602618461842346412633483540142652201486041275081010667260201557331072426444618765328354076766417616130400424781247440566121265103547027280348113585104382410141813131455488838053702550808735183553830446408482367420076160076262663527670655562131264387255352825271342760566005822722332021348641167120856016554505570062536643673516223718301411084856100680157256766330732307710560350275148387768844636817022858087224581570845678335518432524511500037200041260067078007810158777163560526565081510773305010008850376420041473043255445606782654331804225784332044865574631035716102618467576882870067886585833110838276608241427536661612063618063214214585338564232814071202471515401656574782880713574621360444087084720607867137388445835311536257004364542878404634164452864246674118454286683235265786134857158678250347676325587704123207422854256630805386558578714726184126602861672885736446138500463533680748730338560546460428771824557181826464770402317772272740307477181478455585636075313283171573648400013054167571673116613571151510822374601535776316668534781321216853367674808200331442082688114414130302552638734526434061284204530625144825831481633217731670815133456452644081738063826088665353158124242484515531313451650213561416418085410405570606611140402142484384218384741442546410531674164472571000300215641678074334108435802784785688827488005837505826553888287125700643040881844334254155035271475167358430157130007013157486260051048760867051743488768342422141241284763218463632174454765861135173133286717111015542473116471513784372812532572507657618560461160572743554454317855102056287537832510205823506658075100270021761425488164177384714875436784437406006607216702405546421610285706140720336410004242104218828732364102102771261820130415166285786051016867117585071256587118755723107328726422080034138056203686821344515778507367155074361276125362022202351803832562288404317808420748687425723066470647261867532441741436340372734386377387536812712777758741523517725363013063628084148710814544350354128327450370108328345834184825032321204672125621760366274452185311667651381252480486872231627631122044224520137166555015885512810668513134734823527032322425078674033704700366250108836332352873123853430724168550066010372527701608883083567656658420863452247174555607068360358816616025006640012632030424828703053711305501480063563571055808404007667803548310285444582741013521587484871581873111322130771340805727521017815071546438331423181123825712415353283253055676286642757154578338046560888260426388261727558075655358131244258127644363553544161740513858558235265541018757524161706182667583126416834576488658808811147208535624307173833635764341270140176748648145554832612236561605878888234374007627452055011533720070776526077806626462013173033627356313122046445348831353878135766532587562735788641612802888058545633468326114560814135332856327735001740007712770551648528771444277478636812835258726114418280064621578160647816130504484417885455441310710237534854576868640827180867271531761050414728543450007823128426565157434460537338831685013827707746862257354742005884633255324034020140726006706533076110322584488787770046814060435340713051331121572716523741531875356702152315734851311371301664505011838574148782254327851402476184582057271422856838167763147707602848731788351754217448062810632163271832784804754855132333775805410764225072675773831382577208243836676513228533258804277348354423465462726763635586253784211383036438771457456004447381183528835587380018474478558760757488651234458158618285508566384516862071204682088461113757421315271543505317758616335700181150641341681041423844374066773814203773172040015357835077566066406714670073856536132620828836858568272876380471265510617104842623063547546011648218642120528241217201264418272541586085523518764050874346007711882466821876542475180688703464148317887712124820504824573450228111734537748838844660550575520873685472318251758020402465762411066627657844870521057325110206306425246704057182500708712735815425337147147484680845558170616553077740875373516455617458405322418668172025816470204565745732515143276215624473303535601018155746530745157426316131326448006255227746661304883216246242332321221046303207758322108418257570681028241142342484688526201382067331356726675158657337735228036833005140843574828268178828841221231212157311407301862716571557453483027852574588426386317222844845137486524171756112077772450745120438814043882721542500432780173282276283126542113737607746264233325574221587120848174301601886327120664423872308236666445766735274788115256514100204171708047626683537844852541635414486050687783225388745775154057484178630248743026361164786481223116305267273743145576636823725802764406413723436251762165820668803565807826085752366206338232114347130128821066058530265768254726576332032418730118514270183775054023384463034340706331703624150233863615660463048083263785543436400334336168067015171788458623687870730764865344561677627684365730626683072272624257375580502826520477760052580258620807556807623563026603046618634010113234004426635302058856310363212461781161353030781883726554753234473756114056038218043367517243478501237088565228021222257735670338820817870024347425161026158717204583758431002003234356520643035233555762368342114753878281652518156668068054210780825420587461040570476617171708256807440526301021557600786610784666273551445505075683164370060256603831838721252335608240674634433648778570417671457543258352862737344647424385202373703571366236526365774314152542608248523347802566388780166204546612148456535165672332228815853101305036068777746265720610677256370668701517100710332186638861005007310711864876551616102248756707824700427538726774173682441086323064411008186307371752102618060768502607627380178201343326340827013307717005315507127517241727734544314546316826358657803607532512068532335313084167267218766848485772658036626232251228241121145608623508757237303875624836550803486838238480781007152183824603204262111442105822411702738335005015331731517370266458832844686163274513052513143445663445645138422176610067282056232833531362883771248717505343234563001453584106746531048741017055621746366646150773232173061831068888866382201723777873735556684635566885100134773078406037346250430466763014315062572500326680833425582511220020804233713401314545117718084008434041613841270302837200388405753847723837030208332527585875058057764346701453767366355381480582356312063123418762453601741154336354218503285423233032455031888053657637446023116263037806702258215876864326411283205733020423242744783406845233527808618464288404304185036141087678562182326711378025403222216463781711163023683488586425024156028225301534471751801778118254806056605120208110044537253488272220720337416100518705316686511407527862467345875327140732360253782517501523302103632288166835628577115228462686218513817472506280223288028076843513285315285100421633053867834428803443
Output (need to be):
2
Output with my code:
4
So i don't know why is this happening because with another input my code is corrert:
763856354130136657360385516561520873045138714562332581204134142350730376283263680474653368757850487744860687174203110471643858602071801482028332653007166021826745174216138047817365348874514035821835612354050260544684725083051173324643825032336778782315104006603812742522771834088312702426100255155571471164588120604506466482133084060125572828026652740725300255036357264411565411313220610312477661525200624181273678765405170622003760807436012015546647124152462304506772560608127170466866433286314308076111732534314571162487345541117720317272124884630067232072656004285331281425165138177815136175542100311650333707342555832365361622315780463876462585205746384761118882137055072862101805442176434432204100601325362405055835148758015427383385114322832417385874425771288466408276226427662431076007266604531123285610451050580774714271542833845080001436232853660764311085680124630520500408800114274306755821766735740216024032300324714874556435420067888861610242771343152511705731160605244416176738413700221258437380040822775863133651778751211738450223765661576528804555312631150051080343763578868542634554368526333822067137015775230648240813186267232483470047125473601627341053116110277018577025244711848206154630086408583405243377832158881070838386616650275622740201355837112613225167544150076760876686687437824157810643238623035376176626013464366383165881501581054570782377367474818662273085618136500244702754070028836711466505422223042153582382870316175374820780744670187572281053042552333522136522460063685655230321850230236046606221767555035156666348610682685672858283014183766011436704361075434234124456752147833834811110648602534311607828673630167014010214853762411277664048424557438161681445011607235630404341508440814217855744175016074358350272755324876545487473277751734753378553246205084827232261611287686211273427857448171276116864645115258820041275040560465474772146438542184643252602451574158430138262022043256340221757528211417348241661373288441322588327746848234723120818482755778114478603430636437744812250072505662045741313625678162643547645055648750455875223558335531550864588817786283877062284676202818444760857748163561177317405675378462630271604223606503485528758641055610743733564552538477017350144102605615816482412455734188208707163860580652457783450451418444043300857505415584658811074731723222842772371678322840047352361531273433643063677401886518465376222687803576655160317208086728737014667870114387423180387477207077874548373254026433514131254778424332621000552175305788627840866162010103357607727137054058084747135075145827237602602550751458102011542757504244304754386465723634400852226538152618503058603500621173824642882510034110733072422021256507138673714786085262476240218077735880856236785561377704538477286631250223848718761345461341633752202643550117320307780533501404108507037045256817814285738880318564422836322713265887146816632472488385878560804805628138068502684877772080801570500632060020634751026342325005036165116407345860265756521710533601450110421412735046166370148372320354858855384455538852001200854374445327874810443614257318533171054717376752855102715544023273551280125152074823871037368145871374001111231535302078210687378318682248006648721508838864071270124521850040430463883400522814238655721532464053368042308325231264502030277332415144362510551004765254434777074016023140110854150705044415033281723875462545683042636672311863432500166770047028273032140573872737261673537040561630784337778887057476143740442084353580080833202125656344267723845416088835220820667515646872572420878775312107575745736146272106555521815846824608112642577763720502034022730453257700767811115641403014552686583713376027778256317227651825404567287218002523086080745584272785172566847107883166732360335523527877250520503320806348858606613416403242562868868134170620387153750184075382685277380050665544032023508256611047104277202414061004875626872732160248480317523135274231071317823157864623011663460074158680033502364232087046513751083468023635257267054650833816582473255018672115324373688885615605068683541222688784017610105573230674746308533031273056552814124513000128262665062473401424630217637373733542128236222257804358431140848385543085001375202038570856262101241050210166073055253710517487046547410034875606202033638552348687068545265511117105207778805460284233321584680215174150426461481553271732471124010254623404201610852756187412103672523365701581555125811711564383844225110016755403080612043706465700344618037232334153540453325620885466003424385252541244430370845172644232847213164075831524245134122266455733675014648015841781564665867644668464128116876118014752712750125224044762560738758328310758642000310784781871412172284242675178067541777245445383387540503251872434764770305821148084661630038185356686682318115573823042866403346053745751133568124186612871580883151360312847007008803227582374672743037340242823674407413056325542517185021134205620252366775208200064823886422241162006735853868638877477786133821115473824232201760731270667522850856055518462245543117045084503248851351452108403858241240224621533285056474050526630380275753318366727157450481516030125005682800758572356547247382376630120236285023834345010716080585807232401184404273432733020064278337065677335870205730243214740830572468815488584507137422201588308008353171531426283308866806800214083546628483757232554512231325824672637846146753563022676728575472630815131747862511186425175678413017284183600032377523161370615857228426216441670651321508540778103027285046137500830413281336378688114820684128521731657751518010707050357675552862833131164713006157316766532585147545848512145664466825384327114201113147776002142366261715863451642411525744443672043861217872570838088126424703842660226752806113251117174560238451758668525600210428466572842767316114440020052243554778737788862064663107527570807664170301178356786025037282065344006300066664078855573856763811061422417707587557008025483423025004343822287011234803822766765374540728128415248400366271010055714723674140588216153384530018863660481200376560286163083444238846821664406201226132183756850873446843773447472733335215077665786577138366650711538440337532564067211038513804671244304541677234642558862752687483668230813451713230581036554305487517305642341547002727358040231502322872466036573233112623747184701305147102242340461074000525773724681314444385142271831172242282106128821641837683156744828364377363647112668043105072583550110302186243342201435675863146700322312783245383428441532506357751768437250453722567858543037757436640236656643345041366240004761664022458120406517077383828555515000153123758160717474352831261322318407465420124722251650224571051741273403633434427121682671155580627438304044733286166144080510843443210434654852153834353525786424212843238703728783817615413783022718022432362430765676821417632134887667834006275050758051678025305467321844132606841363578310672834682561385251736043687764855173355035767050387255202262057625133562636500800240121100407874682380561057368140666210277655336057248825863816853341401220264668285354666623301326737711808416624103380865072285061540800005633578867821085625382440312055585737571655725738178626514523852136030086076157072710302437601326501508701758620334660245432543270717806880758034411561562683763163887446336155587384861156287657005734074003537654074653284110260676181325412877187528168734666271520607247252180017104088343324182851557471032677342316045738655470618385630116522627780047065281017556067817211275651457420636020808612820273002520306316580586080563558128188742642468043318336130005230352577058242045530768481747604750510611012867040057006446870051788848775665311374278206468757280320708011373885747120848724523673171436440851128532757420240160733240434548705141017533608143251516618205732658701660884504343748236136368085246867605563336508551825123428720853883252733510660325050747501432650003076323428318875525103123137434356727110647711414371827255332160338436255534510431314773718473508346410427014702423645426001156155752248331473813336752367720557038231407815643550056872830401101652154107574123642078818605184710045316822081026630451351732066087022272065254751131317405661547310056786746846138805221860542468231813626752864035880475085446870443858784613175522743543121844224315841131717275131238856855500178161846027605815001653207466463150131437845504411837324633271223806276775836788887173353821742663477644368547522322631308631772514256562461510534174204460016158764173520258202674655813114556774777078355684451231762538050158547751247183067326331384752282005087077028611333236448425020627810852875002736052467018877076654652044773518857242536841427776627164344008385638343411304537522710773676723586276747583433658501462382030027221083345253628151165017160233037611580364630320652162435871653288580314271676653333360626777270565650571515184520714711820167224423218144321611627733108670381586053634252733678450426382040428821735856374531350142554765486757543665158321821383007261711885375675137003616444706840667586544021222623471835765008507254778310230275088584303360822677281326766807302344883372153448072048810210605727424641014752681340304122862118000623188248154823000136522227277782380350202734473771163603184383400581232036372116046503128435120865347764426202814154301366768758374564643418344105136166728157437336147172848745260821852188351620243884055401284041761330855227177266661230258780126438676805778667471105134367300151724600360346203061353503721555243526536271404344130277330186810808260467582358267160641157658556842707151145157068340205342314861111447415621860400101265108166341806166531514636465602458287886752823638272116184053322180418851240228555056026770363502036664525266223086123266114873017123877345603775745244602252250408756513361778067548257582606543455888730834616705438377553157168523144160737216766065215775024027877561707416087530003045453326043720834644705333816324738254088141308802335013715806400077073757385261571831350365578855282768642663651711427602826446068482775202531175770641614332140381017487230605
Output:
1
Your if statement doesn't make sense to me, and your code needs nested loops. The outer loop should repeat until the number has been reduced to be in the 0 to 9 range, and the inner loop should iterate over each digit of the number, calculating the sum of the digits.
Here is my cleaned up and working version:
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
uint64_t sum_of_digits(uint64_t x) {
uint64_t sum = 0;
while (x > 0) {
sum += x % 10;
x /= 10;
}
return sum;
}
int main() {
uint64_t sum = 0;
while (1) {
int c = getchar();
if (!isdigit(c)) { break; }
sum += c - '0';
}
while (sum > 9) { sum = sum_of_digits(sum); }
printf("Result: %d\n", (int)sum);
}
Note: I tried to test this with your 9999-character input vectors but I am getting different results than what you claim is correct. I am getting 9 for the first one and 6 for the second one.
Update: A simpler way using math.
Let's think about what actually happens when you calculate this "digital root".
When you change 10 into 1, you are subtracting 9.
When you change 100 into 1, you are subtracting 99, which is a multiple of 9.
When you change 200 into 2, you are subtracting 2*99, which is still a multiple of 9.
When you change 3578 into 3+5+7+8, you are changing 3000 into 3 and 500 into 5 and 70 into 7, which means you are just subtracting 9 many times.
Everything that this program is supposed to do is just subtract 9 from the number as much as it can, until the number is in the 1 to 9 range. (This is not quite the same as x % 9, but pretty close.)
So we can simplify the program and make it much more efficient by taking advantage of this mathematical fact:
#include <stdio.h>
#include <ctype.h>
int main() {
unsigned int result = 0;
while (1) {
int c = getchar();
if (!isdigit(c)) { break; }
result += c - '0';
if (result > 9) { result -= 9; }
}
printf("Result: %u\n", result);
}
With this new program, I still get 9 and 6 as the answers for your large inputs.
There are multiple issues in your code:
you only allow for up to 99999 digits
you do not check for input failure: undefined behavior if redirected forom an empty file.
type unsigned long long is not required for result, long would suffice as 99999 * 9 is below 231-1.
for full portability, idx should have type size_t.
isdigit(buffer[idx]) has undefined behavior on platforms with signed char if the user typed non ASCII characters.
the first test case posted has 9999 digits and a digit root of 9, not 4 as you post, nor 2 as you expect. The second has a digit root of 6, not 1. There must be some mistake in the data.
Here is a much simpler solution:
#include <ctype.h>
#include <stdio.h>
int main() {
int c, result = 0;
while (isdigit(c = getchar()) {
if ((result += c - '0') > 9)
result -= 9;
}
printf("Result: %d\n", result);
return 0;
}

Why isn't my program that converts decimal to binary printing correctly?

I have an assignment that is asking me to convert a decimal number to its 16-bit 2's complement binary representation stored in a char array. I was provided started code that included a complete main method and an addOne method. I just needed to complete the flipBits and magnitudeToBinary methods.
I have completed the methods and they should work, but I am getting string output. An example is:
Enter integers and convert it to 2's complement binary.
Non-numeric input terminates program.
27
Integer: 27, 2's complement binary:
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void magnitudeToBinary(int n, char arr[], int numOfBits);
void flipBits(char arr[], int numOfBits);
void addOne(char arr[], int numOfBits);
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
//Declare a char array with size 16 to simulate 16-bit binary
int numOfBits = 16;
char arr[numOfBits + 1];
arr[numOfBits] = '\0'; //set the terminating character
//Declare integer n to hold the decimal integer
int n = 0;
puts("Enter integers and convert it to 2's complement binary.");
puts("Non-numeric input terminates program.");
//Continually taking input and convert it to binary
while (scanf("%d", &n) == 1) {//if successfully read in ONE decimal integer
//Initialize the char array to all 0s (leave the terminating character unchanged)
for(int i = 0; i < numOfBits; i ++){
arr[i] = '0';
}
//Convert magnitude (absolute value) to binary
magnitudeToBinary(abs(n), arr, numOfBits);
//if the number is negative: flip all bits, then add 1.
if(n < 0){
//Flip all bits in char arr
flipBits(arr, numOfBits);
//Add 1
addOne(arr, numOfBits);
}
//Output binary:
printf("Integer: %d, 2's complement binary: %s\n", n, arr);
}
return EXIT_SUCCESS;
}
/* addOne: arithmatically add 1 to the binary simulated by character array
* INPUT: char arr[]: the character array holding the binary
* int numOfBits: the number of bits in the binary
* */
void addOne(char arr[], int numOfBits){
/* True table
* ******************************
* carry arr[i] | arr[i] carry
* 1 0 | 1 0
* 1 1 | 0 1
* 0 0 | 0 0
* 0 1 | 1 0
* *********************************/
char carry = '1';
for(int i = numOfBits - 1; i >= 0; i --){
if(carry != arr[i]){
arr[i] = '1';
carry = '0';
}
else if(carry == '1'){
arr[i] = '0';
}
else{
arr[i] = '0';
}
}
return;
}
/* flipBits: perform 1's complement on the binary, i.e., change 1 to 0, 0 to 1
* INPUT: char arr[]: the character array holding the binary
* int numOfBits: the number of bits in the binary *
* */
void flipBits(char arr[], int numOfBits){
//Implement your solution here
for(int i = 0; i < numOfBits; i++) {
if(arr[i] == '1') {
arr[i] = '0';
} else if(arr[i] == '0') {
arr[i] = '1';
}
}
return;
}
/* magnitudeToBinary: Convert a non-negative decimal integer to binary (stored in a char array)
* using division-remainder algorithm
* INPUT: int n: The decimal integer number to be converted
* char arr[]: the character array holding the binary
* int numOfBits: the number of bits in the binary *
* */
void magnitudeToBinary(int n, char arr[], int numOfBits){
//Implement the division-remainder algorithm here
int i = 0;
while (n > 0) {
arr[i] = n % 2;
n = n / 2;
i++;
}
return;
}
I would just like to see the correct binary output. Right now I am unsure if it is an error on my part, my professor's, or if Eclipse is acting up. Any help is appreciated, thanks!
Try changing the line in magnitudeToBinary() from :
arr[i] = n % 2;
to
arr[i] = n % 2 == 1 ? '1' : '0';
You want to write the ASCII value for '1' or '0' into the array - not the result of n % 2.

C - Distinguishing Between Chars and Digits, then Handling Accordingly

I am writing a program that converts user input to either
ASCII values or binary values. If the string contains letters,
each letter should be converted to ASCII. Strings of numbers will
be converted to binary value of entire string. If both letters and
numbers are entered, each letter will be converted to ASCII and the numbers can/will only be separated by letters, for example "32" will print the binary value "00100000", but "3a2" should be converted to "00000011", "97", "00000010".
The way the program is currently written, strings of numbers convert to binary perfectly. However, strings of letters add a decimal "0" to the end. The output converts each letter to its ASCII value, then converts the "0" to binary. I am unsure as to where this "0" is coming from. Additionally, strings beginning
and ending with digits (for example "6j3") will print the ASCII value of j, then the binary value of "6", skipping the "3" entirely and printing the "j" before the "6". I would like to print each ASCII/binary value in the exact order of the user input.
I am posting my entire code for any necessary clarification, but I believe the issue is in the determineChars() function. I am also looking to use the char* letters and char* numbers functions to efficiently handle the appropriate data and store the final num[] and let[] arrays, but I am unsure of how to do this.
I am quite a beginner to C, so excuse the messiness. Corrections, as well as any further optimizations would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// defined in case of booleans
typedef enum { false, true } bool;
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
}
char* numbers(char* input) {
char* num = (char*) malloc(sizeof(char) * 25);
return num;
}
char* letters(char* input) {
char* let = (char*) malloc(sizeof(char) * 25);
return let;
}
void determineChars(char* input) {
int i;
char* num = numbers(input);
char* let = letters(input);
size_t inputSize = getSize(input);
// FOR EACH CHARACTER IN INPUT
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
// stores number values from input into separate array
num[i] = input[i];
printf("\nNumbers: %c", num[i]);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
let[i] = input[i];
printf("\nLetters: %c", let[i]);
// prints separator line + ASCII value
printf("\n\n---------------- %c ------------------", let[i]);
printf("\nASCII Value of %c......... %d", let[i], let[i]);
// removes char from input array
input[i] = ' ';
}
}
// char array must consist of digits only
convertToBinary(num);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
return 0;
}
I would like to print each ASCII/binary value in the exact order of the user input.
In that case, you would have to restructure your code a bit. This is because if the input contains only digits you will have to print binary and alternate being chars and digits if the string contains both. I have tried to do this with the following code, cleaned it up a bit, removed the warnings and memory leaks.
See if this is what you want:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d\n", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
printf("\n");
}
void determineChars(char* input) {
int i;
long ret;
char* ptr;
char c;
size_t inputSize = getSize(input);
ret = strtol(input, &ptr, 10);
if((ret == 0) || ((strlen(ptr) != 0) && (strlen(input) != strlen(ptr))))
{
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
c = input[i];
printf("\nNumber: %c", c);
convertToBinary(&c);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
printf("\nLetter: %c", input[i]);
// prints separator line + ASCII value
printf("\n---------------- %c ------------------\n", input[i]);
printf("ASCII Value of %c......... %d\n", input[i], input[i]);
// removes char from input array
}
}
}
else
convertToBinary(input);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
}
I also tried out the test cases you mentioned in the question along with few others and it seems to work fine.
32
Number of Characters..... 2
---------------- 32 ------------------
ULL...................... 32
Bits..................... 8
Binary Value............. 00100000
3a2
Number of Characters..... 3
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011
Letter: a
---------------- a ------------------
ASCII Value of a......... 97
Number: 2
---------------- 2 ------------------
ULL...................... 2
Bits..................... 8
Binary Value............. 00000010
6j3
Number of Characters..... 3
Number: 6
---------------- 6 ------------------
ULL...................... 6
Bits..................... 8
Binary Value............. 00000110
Letter: j
---------------- j ------------------
ASCII Value of j......... 106
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011

C Converting 4 digit numbers to binary

I want to print the binary equivalent of the numbers from a file in a 20 bit field with spaces after every 4 bits but when the number exceeds 1024 (I've tested this), it no longer outputs in binary but in a base I don't know (i.e. 1234 = 0000 0014 1006 5408)
Here is my code
#include <stdio.h>
long convertToBinary(long);
int main()
{
char binNum[20]; //binary number char array
int i;
long b, decNum; //b is output binary number, decNum is each input number from file
FILE *filePtr;
filePtr = fopen("numbers.txt", "r");
while (!feof(filePtr))
{
fscanf(filePtr, "%li", &decNum);
if (decNum < 0 || decNum > 65535)
{
printf("Error, %5li is out of range.\n", decNum);
continue;
}
b = convertToBinary(decNum); //function call for binary conversion
i = 18;
while (i >= 0)
{
if (i == 4 || i == 9 || i == 14)
{
binNum[i] = ' ';
}
else if (b != 0)
{
binNum[i] = b % 10 + '0';
b /= 10;
}
else
{
binNum[i] = '0';
}
i--;
}
binNum[19] = '.';
printf("The binary representation of %5li is: ", decNum);
for (i = 0; i<20; i++)
{
printf("%c", binNum[i]);
}
printf("\n");
}
return 0;
}
//Recursion function
long convertToBinary(long number)
{
if (number == 0)
{
return 0;
}
else
{
return (number % 2 + 10 * convertToBinary(number / 2));
}
}
The file numbers.txt has numbers like : 0 1 2 3 16 17 1234 5678 65535
Your convertToBinary function is producing a decimal-coded-binary (as opposed to a binary-coded-decimal) which uses a decimal digit per bit.
It looks like long has the same range as int on your system, i.e. 231, which covers ten decimal digits. Once you get eleventh digit, you get an overflow.
Switching to unsigned long long, which has 64 bits, will fix the problem. However, this is sub-optimal: you would be better off writing a to-binary conversion that writes zeros and ones into an array of chars that you provide. You can do it recursively if you'd like, but an iterative solution will do just fine.
Note that the to-binary conversion does not need to insert spaces into char array. This can be done by your main function.

Instead of printing the binary number out how would I store it as a variable?

I pass in a hex number into hex2bin and it prints out the binary number correctly but I don't want it to print out the number I want to return the number so I can use it to find the cardinality of the number. How would I store the number instead of printing it out?
int hex2bin (int n){
int i,k,mask;
for(i = sizeof(int) * 8 - 1; i >= 0; i--){
mask = 1 << i;
k = n & mask;
k == 0 ? printf("0"):printf("1");
}
return 0;
}
Perhaps something like this?
int result = 0;
int i, k...
...
result = result | (((k == 0) ? 0 : 1) << i;
...
return result;
Instead of being clever with an int, you could of course also simply use an array of variables instead.
Store the number in a string whose space is provided by a compound literal (Available since C99).
It works like OP's flow: Loop up to sizeof(int) * 8 times, finding the value of 1 bit and print/save it.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Maximum buffer size needed
#define UTOA_BASE_2 (sizeof(unsigned)*CHAR_BIT + 1)
char *utoa_base2(char *s, unsigned x) {
s += UTOA_BASE_2 - 1;
*s = '\0';
do {
*(--s) = "01"[x % 2];
x /= 2;
} while (x);
return s;
}
#define TO_BASE2(x) utoa_base2((char [UTOA_BASE_2]){0} , (x))
void test(unsigned x) {
printf("base10:%10u base2:%5s ", x, TO_BASE2(x));
char *s = TO_BASE2(x);
// do stuff with `s`, it is valid for until the end of this block
printf("%s\n", s);
}
int main(void) {
test(0);
test(25);
test(UINT_MAX);
}
Sample output
base10: 0 base2: 0 0
base10: 25 base2:11001 11001
base10:4294967295 base2:11111111111111111111111111111111 11111111111111111111111111111111
This is a variation of this base-n answer.
You can use the strcat function to do that.
Note that the new hex2bin function in this answer assumes that the parameter char *buf has already been allocated and can hold at least 1+sizeof(int)*8 bytes including the null terminator:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// assume: buf is at least length 33
int hex2bin (int n, char *buf)
{
int i,k,mask;
for(i = sizeof(int) * 8 - 1; i >= 0; i--){
mask = 1 << i;
k = n & mask;
k == 0 ? strcat(buf, "0") : strcat(buf, "1");
}
return 0;
}
int main()
{
int n = 66555;
char buffer[1+sizeof(int)*8] = { 0 } ;
hex2bin(n, buffer);
printf("%s\n", buffer);
return 0;
}
I hope you will find this helpful :)
bool convertDecimalBNR(INT32 nDecimalValue, UINT32 * punFieldValue, INT32 nBitCount, DecimalBNRType * pDecimalSpecification)
{
bool bBNRConverted = false;
INT32 nBitIndex = nBitCount - 1;
INT32 nBitValue = anTwoExponents[nBitIndex];
*punFieldValue = 0;
if ((nDecimalValue >= pDecimalSpecification->nMinValue) && (nDecimalValue <= pDecimalSpecification->nMaxValue))
{
// if the value is negative, then add (-1 * (2 ^ (nBitCount - 1))) on itself and go on just like a positive value calculation.
if (nDecimalValue < 0)
{
nDecimalValue += nBitValue;
nBitIndex--;
nBitValue /= 2;
*punFieldValue |= BIT_0_ONLY_ONE;
}
while (nBitIndex >= 0)
{
*punFieldValue = (*punFieldValue << 1);
if (nDecimalValue >= nBitValue)
{
nDecimalValue -= nBitValue;
*punFieldValue |= BIT_0_ONLY_ONE;
}
nBitIndex--;
nBitValue /= 2;
}
if (nDecimalValue <= nBitValue)
{
bBNRConverted = true;
}
}
return (bBNRConverted);
}

Resources