Reputation: 21
For example:
char mem[100000];
int reg[8];
mem[36] = 'p'; // add char p to our 36th index of our char array
reg[3] = (int)mem[36]; // store value of mem[36] into reg[3]
Now I want to print the char value at index 3 of that int array.
So far my thought process has lead me to code such as this:
char *c = (char*)reg[3];
cout << *c << endl;
But I am still getting weird values and characters when trying to print it out.
From my understanding, an integer is equal to 4 characters. Since a character is technically a byte and an integer is 4 bytes.
So I am storing a character into my integer array as 4 bytes, but when I pull it out, there is garbage data since the character I inserted is only one byte compared to the index being 4 bytes in size.
Upvotes: 2
Views: 2021
Reputation: 2734
I do not see what is your problem. You store the char into int var. You want to print it back - just cast the value to char and print it
#include <iostream>
int main()
{
char mem[100];
int reg[8];
mem[36] = 'p'; // add char p to our 36th index of our char array
// store value of mem[36] into reg[3]
reg[3] = mem[36];
// store value of mem[36] into reg[4] with cast
reg[4] = static_cast<int>(mem[36]);
std::cout << static_cast<char>(reg[3]) << '\n';
std::cout << static_cast<char>(reg[4]) << '\n';
}
/****************
* Output
$ ./test
p
p
*/
Upvotes: 0
Reputation: 3154
Have you tried this:
char mem[100000];
int reg[8];
mem[36] = 'p'; // add char p to our 36th index of our char array
reg[3] = (int)mem[36]; // store value of mem[36] into reg[3]
char txt[16];
sprintf(txt, "%c", reg[3]); // assigns the value as a char to txt array
cout<<txt<<endl;
This prints out the value 'p'
Upvotes: 1
Reputation: 2978
You shouldn't be using pointers here; it's sufficient to work with char
s:
char c = reg[3];
cout << c << endl;
Note, however, that you could lose information when trying to stuff an int
into a char
variable.
Upvotes: 0