How to store a value in an array using several indexes

hey,
I am working on this project where I need to store a value in an array but it needs to be stored over 4 indexes of the array. The array that I am using to store the number in is a char, so eight bits can be stored at each index.
For example if I have 528968, I need to store eight bits of the number in each index.I have tried the left and right shift operators but am unable to get all bits that the number includes.

1
2
3
4
5
6
7
8
9
10
 int num = 528968;

 char holder[6];

holder[1] = 0x24(01001000)
holder[2] = 0x12(00010010)

holder[3] = 0x08(00001000)
holder[4] = 0x00(00000000)


If anyone can give me any advice on how to handle this, I will greatly appreciate it.

Thanks in Adavance!!!
Simplest way is a cast to treat the array as though it were actually an int in memory, or vice-versa:
1
2
3
int x = 1234567;
char MyArray[sizeof(int)];
*reinterpret_cast<int *>(&(MyArray[0])) = x;
Though in the first place splitting apart multi-byte types is messy because of the big/little endian difference.
Last edited on
If you had problems with bitshifting, maybe you used signed char array? Try this:
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
#include <iostream>
using namespace std;

int main()
{
	unsigned char holder[4];	// Make this unsigned!!! 

	// to split
	int x = -528968;
	for (int i = 0; i < sizeof(x); i++)
		holder[i] = x >> (i*8);

	// to reassemble
	int y = 0;
	for (int i = 0; i < sizeof(y); i++)
		y += holder[i] << (i*8); 
		
	// Check
	cout << "Your X in hex: " << hex << x << endl;	
	for (int j = 0; j <4; j++ )
		cout << "holder[" << j << "]: " << hex 
                     << static_cast<int>(holder[j]) << endl;

	cout << "\nYour Y: " << y << endl << endl;

	system("pause");
}
Last edited on
Topic archived. No new replies allowed.