将 Int 转换为 Char * 并返回 C

问题描述 投票:0回答:1

编辑:我编辑了我的问题以修复一些错误并使我想要做的事情更清楚。

我想将 4 字节整数转换为长度恰好为 4 字节的 char *,然后再转换回 int。我知道人类无法以 char * 形式读取整数。

我的代码如下所示:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void intToStr (int32_t i, char ** s) {
    *s = (char *) i;
}

void strToInt (char * s, int32_t * i) {
    *i = (int32_t) s;
}

int main () {

    // Works?

    int32_t a = 5;
    char * b = malloc(4);
    intToStr(a, &b);

    int32_t c = 0;
    strToInt(b, &c);

    printf("%d\n", c);

    // Segfault

    char* s = malloc(64);
    memcpy(s, "00000000000000000000000000000000000000000000000000000000000000", 64);
    memcpy(s + 4, b, 4);
    char * d = malloc(4);
    memcpy(d, s + 4, 4);
    int32_t e = 0;
    strToInt(d, &e);

    printf("%d\n", e);
}

这个输出

5
Segmentation Fault

相反,我希望能够将 int 转换为长度为 4 的 char * ,将其存储到更大的 char * (可能包含其他数据)中,然后将其转换回 int 。

进一步编辑:

我根据建议尝试了其他方法:

void intToStr (int32_t i, char * s) {
    * (int32_t *) s = i;
}

void strToInt (char * s, int32_t * i) {
    * (char **) i = s;
}

int main () {

    int32_t a = 5;
    char * b = malloc(4);
    intToStr(a, b);

    int32_t c = 0;
    strToInt(b, &c);

    printf("%d\n", c);

    char* s = malloc(64);
    memcpy(s, "00000000000000000000000000000000000000000000000000000000000000", 64);
    memcpy(s + 4, b, 4);
    printf("%s\n", s);
    char * d = malloc(4);
    memcpy(d, s + 4, 4);
    int32_t e = 0;
    strToInt(d, &e);

    printf("%d\n", e);

}

现在输出:

[Random Large Int]
0000[?]
[Same Int]
c char int32
1个回答
2
投票
  1. 要访问
    int
    二进制表示形式
    char
    s 就足够了:
int x ;
char *c = (char *)&i;

但是要以相反的方向执行此操作,您需要将

memcpy
数组转换为
char
数字。否则,您可能会违反严格别名规则
int

© www.soinside.com 2019 - 2024. All rights reserved.