Advertisement
gur111

dec2base4

Aug 9th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.74 KB | None | 0 0
  1. /* Converts base dec to base4. Returns as string */
  2. char* dec2base4(unsigned long num){
  3.     /* Allocates memory for output string */
  4.     char *out = malloc(MAX_NUM_SIZE);
  5.     /* The charset of the output base */
  6.     char dict[4] = {'0','1','2','3'};
  7.     int i;
  8.     /* Set ALL chars to "0" (or first in charset) so characters that we won't
  9.         reach will not be skipped */
  10.     memset(out, dict[0], MAX_NUM_SIZE);
  11.     /* Let's not forget about NULL string termination */
  12.     out[MAX_NUM_SIZE-1] = '\0';
  13.     for(i = 0; num; i++, num=num>>2){
  14.         /* The magic: Takes the last 2 bin digits of num and take the
  15.             coresponding char from the charset */
  16.         out[MAX_NUM_SIZE-2-i] = dict[num&3];
  17.     }
  18.    
  19.     return out;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement