0
Follow
2
View

Can you decipher how this code works?

kritos 注册会员
2023-02-28 18:36

union is like a struct except that all its members share the same memory
so when you assign a value to float, the corresponding char has a value, The reverse is also true
The rest is nothing more than how the 4 bytes of int are converted to binary and how the 4 bytes of float are converted to binary
is the most basic in the book, simply understand, know the principle is easier to understand, can be written really no need

dongfan_hr 注册会员
2023-02-28 18:36

union, in which all members share the same memory and store the same data, but the results are different when the data is converted to different types.

diroya 注册会员
2023-02-28 18:36

A simple point is to convert a 32-bit hexadecimal number to decimal output, because it may involve big endian byte or small endian byte problems, so the program annotation has been explained.
Is that clear?

isabel333 注册会员
2023-02-28 18:36

Also, if you're not familiar with federation, review it.

dqsbl2010 注册会员
2023-02-28 18:36

  • What this code does is represent a 32-bit IEEE 754 standard floating point number as a 4-byte array of unsigned characters and restore the floating point number from the hexadecimal character array.
  • Specifically, the program uses an association valReg to represent a 32-bit floating-point number and a 4-byte array of unsigned characters. This means that different member variables of the union use the same memory space. In the program, we can set the hexadecimal representation of the floating-point number by setting the val.data array. We can also set the value of the floating-point number directly by setting val.fval.
  • In main we first create an instance of val. We then set each element of the val.data array, where each element represents one byte of a 4-byte floating-point number. Specifically, we set val.data[3] to 0x41, val.data[2] to 0xf7, val.data[1] to 0xae, and val.data[0] to 0x14. Together, these values represent an IEEE 754 standard floating point number.

Finally, we use the printf function to print the value of val.fval to the screen in decimal form. Note that because val.data and val.fval use the same memory space, val.fval here represents the value after interpreting val.data as a floating-point number.

  • Because different systems may have different byte order, we also need to swap byte order in the program. In this example, we assume small endian byte order, that is, the least significant byte comes first. If it is big endian, we need to swap the order of the bytes.

About the Author

Question Info

Publish Time
2023-02-28 18:36
Update Time
2023-02-28 18:36