这两天还在读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;
}

猜你喜欢

转载自blog.csdn.net/weixin_39410618/article/details/83033218