少女祈祷中...

整形间的进制转换

  1. 使用输入输出格式说明符:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    int a = 07442313637;
    int b = 1015650207;
    int c = 0x3c89979f;

    printf("方法一:\n");
    // 16进制 运行结果:3c89979f 3C89979F
    printf("%x %X\n", a, b);
    // 8进制 运行结果:7442313637 7442313637
    printf("%o %o\n", b, c);
    // 10进制 运行结果:1015650207 1015650207
    printf("%d %d\n", a, c);
  2. 使用栈进行转换:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    #include <stdio.h>
    #include <malloc.h>

    typedef struct
    {
    char data[10];
    int top;
    int bottom;
    } stack;

    stack *StackCreate()
    {
    stack *p = (stack *)malloc(sizeof(stack));
    if (p == NULL)
    {
    return 0;
    }
    p->bottom = p->top = 0;
    return p;
    }
    void StackInput(stack *p, char str)
    {
    p->data[p->top] = str;
    p->top++;
    }
    char StackOutput(stack *p, char str)
    {
    if (p->top != p->bottom)
    {
    str = p->data[p->top - 1];
    p->top--;
    return str;
    }
    }
    void StackPrint(stack *p)
    {
    while (p->top != p->bottom)
    {
    printf("%c", p->data[p->top - 1]);
    p->top--;
    }
    }

    int main()
    {
    int b = 1015650207;

    printf("方法二:\n");
    // 16进制,修改base和index实现其他进制
    int base = 16;
    char index[] = "0123456789abcdef";
    int last = 0;
    stack *p;
    p = StackCreate();
    while (b > 0)
    {
    last = b % base;
    StackInput(p, index[last]);
    b = (b - last) / base;
    }
    StackPrint(p);
    return 0;
    }

数值字符串转换为整形

  1. 通过遍历字符数组来匹配对应字符,并返回相应下标。需要注意的是循环遍历的时候要保证少一次循环,以确保最后一位数只进行加操作。代码如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    // 字符串转整形 运行结果:1015650207
    printf("字符串转整形:\n");
    char index[] = "0123456789abcdef";
    int base = 16;
    char d[] = "3c89979f";
    int i = 0;
    int j = 0;
    int tj = 0;
    long result = 0;
    while (d[i] != '\0')
    {
    j = 0;
    while (index[j] != '\0')
    {
    if (index[j] == d[i])
    {
    break;
    }
    j++;
    }
    result = (result + tj) * base;
    tj = j;
    i++;
    }
    result += tj;
    printf("%d", result);