In: Computer Science
I have char memory[1024]. i want to write integer value of 300 into the memory. Type casting worked ok for all values 0-127. above that it looks like a garbage. could you write a function in c++ that will write an integer value say 300 into the memory. Thank you.
Char memory[1024] initiates character value. So if you store an integer in the character array it will act as a character but it will remain an integer for you.
Use the ‘unsigned char’ for memory optimization method.Developers generally use int to store integer values, without thinking about data range, if the data range is less, we should use unsigned char,
A type of char data type, unsigned char can store values between 0 to 255, so we can use unsigned char instead of short or int.
#include <stdio.h>
int main()
{
unsigned char value=0;
printf("Value is: %d\n",value);
value=50;
printf("Value is: %d\n",value);
value=255;
printf("Value is: %d\n",value);
return 0;
}
Output
Value is: 0 Value is: 50 Value is: 255
What will happen, if the value is greater than 255?
int main()
{
unsigned char value=300;
printf("Value is: %d\n",value);
return 0;
}
Output
value is: 44
Why?
Unsigned char store only 8 bits data into the memory, when the value is greater than only first 8 bits will be stored, see the given image.
In this image 8 bits value is: 0010 1100 which is equivalent to 44.