进制转换代码(支持长二进制):
Blist.h
Blist.h
#pragma once
#define ok 1
#define error 0
#define true 1
#define false 0
#define overflow -2
#define MAXSIZE 100
typedef int Status;
typedef struct BNode {
int data;
struct BNode *pre, *next;
}BNode,*Position;
typedef struct {
BNode *head;
BNode *tail;
}Blist;
建立链表函数:
#include "Blist.h"
#include <stdio.h>
Status InitBlist(Blist &BL) {//建立双链表
BNode *p, *q;
p = (BNode *)malloc(sizeof(BNode));
if (!p) exit(overflow);
p->data = NULL;
q = (BNode *)malloc(sizeof(BNode));
if (!q) exit(overflow);
q->data = NULL;
p->next = p->pre = q;
q->next = q->pre = p;
BL.head = p; BL.tail = q;
return ok;
}
Status AddElem(Blist &BL, long e) {//插入e到双链表中
BNode *p;
p = (BNode *)malloc(sizeof(BNode));
if (!p) exit(overflow);
p->data = e;
p->next = BL.head->next; BL.head->next = p;//头尾链接
p->pre = p->next->pre; p->next->pre = p;
}
void PrtBlist(Blist BL, char p) {//打印双链表
Position q;
switch (p) {//通过p判断从头打印还是从尾打印
case 'H': {//从头
q = BL.head->next;
while (q->next != BL.head) {//
printf("%ld", q->data);
q = q->next;
}//
break;
}//
case 'T': {//从尾
q = BL.tail->pre;
while (q->pre != BL.tail) {//
printf("%d", q->data);
q = q->pre;
}//
}//
}//
}//
主区:
#include <stdio.h>
#include <math.h>
#include "Blist.h"
//-------函数声明
long BtoD(long);
long DtoB(long);
long Len(long);
//--------外部函数声明
extern Status InitBlist(Blist &BL);
extern Status AddElem(Blist &BL, long e);
extern void PrtBlist(Blist BL, char p);
//-----------主函数
int main() {
long B;
char J;
long (*p)(long);//函数指针
scanf("%c%ld", &J,&B);
switch (J) {
case'B':p = BtoD; printf("%ld", (*p)(B)); break;
case'D':p = DtoB; (*p)(B); break;
}
return 0;
}
//-----------函数定义
long DtoB(long a) {//十进制转二进制
Blist BL;
int i;
long r=a,p,H=0;
InitBlist(BL);
for (i = 0; r != 0; i++) {
p = r % 2;//先求余
r = r/2;//再求整除
//H += p * pow(10, i);//相加
AddElem(BL, p);
}
PrtBlist(BL,'H');
return ok;
}
long BtoD(long D) {//二进制转十进制
int i,H=0,r=D;
int le,p;
le = Len(D);
for (i = le; i >= 0; i--) {
p = r / pow(10, i-1);//求位次上的数,如1234的1
r = r - p*pow(10, i - 1);//求退一位的余,如从1234求得234
H += p * pow(2,i-1);
}
return H;
}
long Len(long NUM) {
int i=0;
do{
NUM = NUM / 10;
i++;
} while (NUM!=0);
return i;
}
/*心得:
1.可以通过注释标记判断括号匹配情况;
2.加入双链接结构使程序复杂,但是能够输出长二进制
*/