Use Pointers and Casting to insert/retrieve char(s) and int(s) from char array

I'm at a complete loss here on how to do this. I have a char array of 100 bytes and I'm trying to use ptrs and casting to put integer(s) and char(s) into and retrieve from this array (essential simulating memory).

Simulated Array:
Say I have [ | | | a | b | c | d | | | ... | ]

I want to be able to take those four chars and convert them into one 32 bit integer and using a pointer, insert that 32 bit integer back into the array so that | a | b | c | d | shows up again. Here's a visual

[ | | | a | b | c | d | | | ... | a | b | c | d | | | | ]

1
2
3
4
5
6
7
8
9
10
char memory[100];
int i, j, *ii;
char c, *cc;

mem[3] = 'a';
mem[4] = 'b';
mem[5] = 'c';
mem[6] = 'd';

i = ?? // Not sure what to put here. 


I know that each char is a byte and that an int is made up of 4 bytes so somehow I need to figure out how:

32bit (4 bytes) INT = 1st byte = 'a' 2nd byte = 'b' 3rd byte = 'c' 4th byte = 'd'

I hope this makes sense. I feel like I've been on the hamster wheel getting nowhere all day.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>

int main() {
    char mem[100];

    mem[3] = 'a';
    mem[4] = 'b';
    mem[5] = 'c';
    mem[6] = 'd';

    int i = *(int*)&mem[3];
    std::cout << i << "\t0x" << std::hex << i << '\n';
    
    *(int*)&mem[50] = i;
    
    std::cout << mem[50] << mem[51] << mem[52] << mem[53] << '\n';
}

ints are not guaranteed to be 4 bytes, but it is common on the common platforms. Really you should use int32_t (or perhaps uint32_t).

Also, it's technically undefined behavior to dereference a "type-punned" pointer, so it's not guaranteed to actually work as you might want. And there could even be alignment problems on some platforms.

As helios mentions (see next post) there are also endian issues. And note that he uses memcpy to get around both the alignment and the type-punning problem. That's the proper way to do it (in essence, treating everything like chars).
Last edited on
1
2
memcpy(&i, mem + 3, sizeof(i)); //copy from mem to i
memcpy(mem + x, &i, sizeof(i)); //copy from i back to mem, at a different location 
Note that after the first memcpy(), the contents of i are platform-specific. Not only may ints be larger or smaller (on some platforms, sizeof(int) is 2, on others it may be bigger than 4), but they may be stored in memory differently.
1
2
3
4
memcpy(&i, mem + 3, sizeof(i));
bool is_little_endian =  (i & 0xFF) == 'a';
bool is_big_endian =  (i & 0xFF) == 'd';
bool is_weird = !is_little_endian && !is_big_endian;
Thanks! This is a big help. I'm going to review this to make sure I understand everything that is going on here. If I have any questions, I'll post them. Once again, thank you!
Topic archived. No new replies allowed.