Edit: I've edited my question to fix some mistakes and make what I want to do clearer.
I want to convert a 4 byte integer into a char * of length exactly 4 bytes and then back to an int. I understand the integer won't be human readable in char * form.
My code looks like this:
#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);
}
This outputs
5
Segmentation Fault
Instead, I want to be able to cast the int into a char * of length 4, store that into a larger char * (with potentially other data) and then convert it back into an int.
Further Edit:
I've tried something else based on suggestions:
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);
}
Which now outputs:
[Random Large Int]
0000[?]
[Same Int]
int
binary representation as char
s it is enougt to:int x ;
char *c = (char *)&i;
or to copy use memcpy
int x = something;
char c[sizeof(x)];
memcpy(c, &x, sizeof(x));
But to do this in the opposite direction you need to memcpy
the char
array into an int
number. Otherwise, you might violate strict-aliasing rules
int x ;
char c[sizeof(x)];
/* .... */
memcpy(&x, c, sizeof(x));