string - C -- Filling char * using a loop and index --- NOT WORKING -


this chunk of code part of function convert decimal number binary, placing in specific index of char instbin[33] created , passed reference calling function. passes in decimal number, number of binary digits you'd (appending 0's front of given bin number). i've been fiddling while , can't place 0's , 1's array. i've gotten way down realizing instbin[i] = '1'; isn't working @ -- when print instbin, nothing has happened. i've looked @ other examples doing type of thing, seems giving array of characters variable when selecting index should work... thoughts why mine isn't?

int printbin(int num, int numbits, int startindex, char * instbin){     int r, i; /* r remainder, index */ const int fail = 0; = startindex + numbits; /* start indexing @ end of current segment */ while (num > 0) {     /* long >= startindex, can still add array */     if (i >= startindex){         r = num % 2; /* find remainder */         if (r == 1)             instbin[i] = '1';         else /* r == 0 */             instbin[i] = '0';         num /= 2; /* divide number */         i--;     }     else /* num big fit in given number of bits */     return fail; } /* return 1 success*/ return 1; } 

there 2 major problems. first fencepost error. assuming intent significant bit put buffer @ startindex, need start i = startindex + numbits - 1. think through example numbits = 1 if need convincing of this.

the second problem when number small enough need leading zeros, loop doesn't provide them. provides 1 digit @ time until number hits 0, stops. need second loop after main loop, add zeros. if @ value of i after main loop, tells main loop stopped, can finish job this:

while(i >= startindex)     instbin[i--] = '0'; 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -