1. 程式人生 > >這兩天還在讀x86保護模式的天書了,不過閒暇寫了個二進位制字串轉化為二進位制數的幼稚程式。

這兩天還在讀x86保護模式的天書了,不過閒暇寫了個二進位制字串轉化為二進位制數的幼稚程式。

 當然是方便自己查那些什麼特權級,描述符,粒度位,段屬性之類的資訊了。

#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)];
		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;
}