long double i, *ptr;
ptr = &i;
I want to modify the value of byte No. 4. Size of long double is 8 byte. So is it possible by subtracting 4 from *ptr ? i.e
(ptr)-4 = 9;
long double i, *ptr;
ptr = &i;
I want to modify the value of byte No. 4. Size of long double is 8 byte. So is it possible by subtracting 4 from *ptr ? i.e
(ptr)-4 = 9;
You can access the bytes that represent an object by converting a pointer to the object to a pointer to unsigned char
and then accessing bytes through that pointer. For example, the fourth byte of i
could be set to 9 by:
unsigned char *p = (unsigned char *) &i;
*(p+4) = 9;
However, you should not do this without good reason. It runs into portability problems and should only be done for special purposes and with careful attention to the C standard and/or the documentation of your C implementation. If you explain further why you want to do something like this, it might be possible to show better ways of doing it or to explain the hazards.
Note that the correct address for byte four (starting numbering at byte zero) is p+4
, not p-4
as used in the question.
I would attempt something more readable
union {
long double d;
char v[sizeof(long double)];
} x;
x.d = 1234567890;
std::cout << x.d << ' ' << int(x.v[6]) << std::endl;
x.v[6] = 0xCC;
std::cout << x.d << ' ' << int(x.v[6]) << std::endl;
yields
1.23457e+09 44
1.23981e+09 -52
(*ptr)-4 = 9
is not permitted because it leads to RValue violation (Right hand side of an assignment operation cannot be another operation).
But you can use bit operations like:
(*ptr) = (*ptr) & 0x00009000;
First see here: How do you set only certain bits of a byte in C without affecting the rest?. The idea is to clear the byte you are interested in, and then set your value with an or operation. So in your case you'd do:
val &= ~0xff; // Clear lower byte
val |= 9 & 0xff; // Set Nine into the least significant byte.