Click here to Skip to main content
15,908,909 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
What is the best way to move value directly to 2 char rooms?

char a[2];

I want to move the value of '0xff00' to this room like as follows but failed.

a[0] = '0xff';
a[1] = '0x00'; // or a[1] = 0;

I want to know the method to insert directly hex value to any other char memory spaces....

What I have tried:

More than 4 hours wasted to solve this problem but failed.
Posted
Updated 20-May-16 8:42am
Comments
Sergey Alexandrovich Kryukov 20-May-16 14:14pm    
The question would only make some sense of your tell us how where '0xff00' comes from.
As soon as '0xff00', '0xff' or '0x00' are fixed statically known literals, there is no a problem. You use each as an immediate constant, that is (which is generally bad). To formulate your problem, you need to show how a variable is declared. Or, alternatively, you should explain what you want to achieve with that.
—SA
Richard MacCutchan 21-May-16 4:27am    
You have not explained why those move statements are wrong or not working.

1 solution

There are a number of problems here: char quantities are aligned on byte boundaries, but integers aren't - they are aligned on word boundaries.
What that means is that the address of a char based value can be 0, 1, 2, 3, 4, 5, 6 ... but the address of an integer can only be 0, 4, 8, 16, ...
The reason for this has to do with how the processor works and how memory is actually addressed. Trying to "stuff" an integer value into a char based address can easily end up with other memory getting corrupted, or the wrong values going into the wrong locations.
If that wasn't the case, you could just go:
C++
int *pi = (int *)a;
*pi = 0xff00;
But...even if that worked because the addresses were fine there would be another problem: Endianness. The PC processor is what is called "Little Endian", which means that it stores the least significant byte of a value in the lowest order address: so the value would go in the wrong way round, with 0x00 in a[0], and 0xFF in a[1]. (Even if it wasn't, since most processors are 32 or 64 bit these days with very few being 16 bit, it would still not get the right values in the right locations.

But...you can do it:
C#
unsigned char a[2];
int i = 0xFF00;
a[0] = (unsigned char) (i >> 8);
a[1] = (unsigned char) (i & 0xFF);
It's just probably not a useful thing to do! :laugh:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900