自己练练了手,写了两个程序:
第一个:十进制的数字转化为16进制
- int main(int argc, _TCHAR* argv[])
- {
- int a = 100000000, i = 0, b;
- int c[8] = {0};
- printf("%10.4x ", a);
- while (a) {
- b = a - (a>>4<<4);
- c[i] = b;
- i++;
- a = a>>4;
- }
- i = i - 1;
- printf("The number of hex is: ");
- for (int index = i; index >= 0; index--)
- printf("%x", c[index]);
- printf(" ");
- return 0;
- }
第二个,将ascII字符转化为十进制数字, 不是数字的转化!
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- int main() {
- char *str = "asd";
- const int N = strlen(str);
- int *array = new int[N-1];
- int i = 0;
- while (*str != '/0') {
- array[i] = (int)(*str); //直接转化存储即可
- cout << array[i] << endl;
- i++;
- str++;
- }
- }
3、数字的转化为字符串,字符串转为数字:
- #include<stdio.h>
- #include<stdlib.h>
- char *i_to_a(int value) {
- char temp[30];
- char* result;
- int i=0,j=0;
- while(value!=0){
- temp[i]=value%10+48;
- value/=10;
- i++;
- }
- result =(char*)malloc(sizeof(char)*(i+1));
- for(j=0;j<i;j++){
- result[j]=temp[i-1-j];
- }
- result[j]='/0';
- return result;
- }
- bool a_to_i(char *a, int *num) {
- char *p = a;
- int i = 0;
- *num = 0;
- //check the string
- if ( (*p == '+') || (*p == '-') )
- i = 1;
- while (*(p + i) != '/0') {
- if (*(p+i)>='0' && *(p+i)<='9') {
- i++;
- }
- else {
- printf("Illegall!/n");
- return 1;
- }
- }
- if (i == 1) {
- printf("Illegall!/n");
- return 1;
- }
- //start converting, here the string is in a right formulation
- while (*p != '/0') {
- if ( (*p == '+') || (*p == '-') ) {
- p++;
- }
- else {
- *num = *num * 10 + *p -'0';
- p++;
- }
- }
- if (*a == '-') {
- *num = -(*num);
- }
- else {
- }
- return 0;
- }
- int main() {
- int i=6553567;
- char* p = i_to_a(i);
- printf("%s/n",p);
- free(p);
- int num = 0;
- if ( !a_to_i("0000", &num))
- printf("num = %d/n", num);
- return 0;
- }
4 数字的转化为字符串,字符串转为数字(2):
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void myitoa_first(long long a, char *p) {
- if (a == 0)
- {
- *p = '/0';
- }
- else {
- myitoa_first(a/10, p+1);
- *p = a%10 + '0';
- }
- }
- void myitoa_second(char *p) {
- char *p1 = p;
- char *p2 = p + strlen(p) - 1;
- int a;
- while (p1 < p2)
- {
- a = *p2;
- *p2 = *p1;
- *p1 = a;
- p1++;
- p2--;
- }
- }
- void myitoa(long long a, char *p) {
- myitoa_first(a, p);
- myitoa_second(p);
- }
- int myatoi(char *pp) {
- char *p = pp;
- int sum = 0;
- bool flag = 0;
- if (*p == '+')
- {
- flag = 0;
- p++;
- }
- else if (*p == '-')
- {
- flag = 1;
- p++;
- }
- while (*p != '/0')
- {
- if (*p >= '0' && *p <= '9')
- {
- sum = sum *10 +*p - '0';
- p++;
- }
- else
- break;
- }
- if (flag)
- {
- sum *= -1;
- }
- return sum;
- }
- int main() {
- char *p = (char *)malloc(32 * sizeof(char) );
- long long a = 12345;
- myitoa(a, p);
- printf(p);
- puts("");
- char *pp = "-1234567s89";
- int aa = myatoi(pp);
- printf("a = %d/n", aa);
- }