前面那个二进制数显示的程序,自己发现了bug,不过没找到原因,大家帮忙看下吧
#include <stdio.h>
#include "const.h"
//#include "global.h"
//#include "proc.h"
//#include "protect.h"
//#include "proto.h"
//#include "string.h"
#include "type.h"
unsigned int do_div(unsigned int *value, unsigned int base);
char *printbin(unsigned int value);
int str_len(char *str);
int str2bin(char *str);
int main(void) {
printf("1 << 3 = 0x%x\n", 1 << 3);
printf("%s\n", printbin(0xffffffff));
printf("%s\n", printbin(0x9a));
printf("%d\t 0x%x", str2bin("11111111"), str2bin("11111111"));
printf("%d\t 0x%x", str2bin("c111"), str2bin("c111"));
}
unsigned int do_div(unsigned int *value, unsigned int base) {
unsigned int temp;
temp = *value % base;
*value = *value / base;
return temp;
}
char *printbin(unsigned int value) {
char str[2] = "01";
char tempa[128], tempb[128];
char *temp1 = tempa, *temp2 = tempb;
int count = 0;
int count1 = 0;
if(!value) {
*temp2++ = '0';
}
while(value) {
*temp1++ = str[do_div(&value, 2)];
//在这里,如果不加上去的话,显示乱码,不知道为何
// printf(" %c ", *(temp1 - 1));
count++;
if(count % 4 == 0) {
*temp1++ = ',';
count1++;
}
}
if (*(temp1 - 1) == ',') {
temp1--;
count1--;
}
count += count1;
while(count) {
*temp2++ = *--temp1;
count--;
}
*temp2++ = 'b';
*temp2 = '\0';
temp2 = tempb;
return temp2;
}
int str_len(char *str) {
int len = 0;
while(*str) {
str++;
len++;
}
return len;
}
int str2bin(char *str) {
int i = 0, len, result = 0;
len = str_len(str);
char temp[128], *temp1 = temp, c;
for (i = len - 1; i >= 0; i--) {
*temp1++ = str[i];
if((str[i] < '0') || (str[i] > '1')) {
printf("ERROR String Format!, %c\n!!!!!!!!!!!!!!!!!\n", str[i]);
return -1;
}
}
*temp1 = '\0';
c = temp[0] - '0';
if(len == 1) {
return (int)c;
}
for (i = 1; i < len; i++) {
result += (temp[i] - '0') * (2 << (i - 1));
}
result += c;
return result;
}