There is a number of float. It is necessary to write a program that replaces the last byte in the representation of this number with the value "0xAA" and, after the change, displays the new number (obtained as a result of the change). I would be grateful for your help.

enter image description here

Closed due to the fact that off-topic participants Harry , Abyx , αλεχολυτ , Bald , Kromster 22 Dec '16 at 4:10 .

  • Most likely, this question does not correspond to the subject of Stack Overflow in Russian, according to the rules described in the certificate .
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 3
    This question should be closed, because there is not even an attempt to think for yourself ... - Harry
  • one
    And what did you try to do to solve this problem? What exactly you can not? - Vadim Ovchinnikov

2 answers 2

It is not clear, the high or low byte ... Therefore, I wrote for both.

int main() { assert(sizeof(float) == sizeof(unsigned int)); float f,save; scanf("%f",&f); save = f; unsigned int * p = (unsigned int *)&f; printf("%10f %08X\n",f,*p); *p = (*p&0xFFFFFF00) | 0xAA; // Младший байт printf("%10f %08X\n",f,*p); f = save; *p = (*p&0x00FFFFFF) | (0xAA << 24); // Старший байт printf("%10f %08X\n",f,*p); } 

    You can use the following approach

     #include <iostream> #include <iomanip> #include <cstdint> //... float x = 123.456789; std::cout << "x = " << std::setprecision(16) << x << std::endl; std::cout << "x = " << std::hex << reinterpret_cast<uint32_t &>( x ) << std::endl; reinterpret_cast<uint32_t &>(x) &= ~(uint32_t)0 << 8; std::cout << "x = " << std::setprecision( 16 ) << x << std::endl; std::cout << "x = " << std::hex << reinterpret_cast<uint32_t &>(x) << std::endl; reinterpret_cast<uint32_t &>(x) |= (uint32_t)0xAA; std::cout << "x = " << std::setprecision(16) << x << std::endl; std::cout << "x = " << std::hex << reinterpret_cast<uint32_t &>(x) << std::endl; 

    The output of this code snippet may look like

     x = 123.456787109375 x = 42f6e9e0 x = 123.455078125 x = 42f6e900 x = 123.4563751220703 x = 42f6e9aa 

    Or the same can be done using a pointer. for example

     float x = 123.456789; uint32_t *px = reinterpret_cast<uint32_t *>(&x); std::cout << "x = " << std::setprecision(16) << x << std::endl; std::cout << "x = " << std::hex << *px << std::endl; *px &= ~(uint32_t)0 << 8; std::cout << "x = " << std::setprecision( 16 ) << x << std::endl; std::cout << "x = " << std::hex << *px << std::endl; *px |= (uint32_t)0xAA; std::cout << "x = " << std::setprecision(16) << x << std::endl; std::cout << "x = " << std::hex << *px << std::endl; 

    The output to the console of this code fragment will be the same as shown above.