Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <stdlib.h>
- #include <stdio.h>
- #define ipow(n, e) (int)pow(n, e)
- #define buf_update(n) printf("buf: %d\n", n)
- #define error(msg) fprintf(stderr, "%s", (msg) )
- void
- _conbase_negbase(int n, int r, int e)
- {
- int m;
- /* Find minimum multiplicator of |r^e| that is > |n| */
- for (m = 0; m * abs(ipow(r, e)) < abs(n); ++m) {
- ;
- }
- buf_update(m);
- if (e && n) {
- /* Must not use absolute values here ! */
- _conbase_negbase(n - (m * ipow(r, e)), r, e - 1);
- }
- return;
- }
- void
- _conbase_posbase (int n, int r)
- {
- if ( n ) {
- _conbase_posbase(n / r, r);
- buf_update(n % r);
- }
- }
- void
- conbase(int n, int r)
- {
- int _exp = -1;
- int _pow;
- int _powpos = 0;
- int _npos = 0;
- if ( r < 0 ) {
- do {
- _pow = ipow(r, ++_exp);
- _powpos = (_pow>=0)?1:0;
- _npos = (n>=0)?1:0;
- if ( abs(_pow) > abs(n) ) {
- if ((!_powpos && !_npos) || (_powpos && _npos)){
- break;
- } else if ((_powpos && !_npos) || (!_powpos && _npos) ) {
- _exp--;
- break;
- }
- }
- } while (1);
- _conbase_negbase(n, r, _exp);
- }// r < 0
- else if ( r > 1 ) {
- _conbase_posbase(n, r);
- }// r > 1
- else {
- error("conbase: bad base.\n");
- }// r == 0 || r == 1
- }
- int
- main(int argc, char **argv)
- {
- printf("<\n");
- conbase(1240, -10);
- printf("<\n");
- conbase(124, -10);
- printf("<\n");
- conbase(-1240, -10);
- printf("<\n");
- conbase(-124, -10);
- printf("<\n");
- conbase(-10, -10);
- /* Positive base */
- printf("<\n");
- conbase(1240, 10);
- printf("<\n");
- conbase(124, 10);
- printf("<\n");
- conbase(10, 10);
- printf("<\n");
- conbase(127, 8);
- printf("<\n");
- conbase(32767, 2);
- printf("<\n");
- conbase(-32768, 2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement