简体   繁体   中英

Extracting the byte value of double from memory

I'm trying to extract the byte value of a double from the computer's memory. The reason for this is accuracy, as the final value that is represented to the user has some rounding performed.

Ideally, I want to be able to extract the sign, exponent and mantissa from the number (IEEE 754 standard)

From what I understand, casting to an unsigned char is the way to go. I have the following code snippet (stolen elsewhere), but I don't trust the results - there's no byte output for any integer values:

double d = 2;
unsigned char *p = (unsigned char*)&d;

Can anyone guide me in the right direction in order to extract byte representation of double numbers accurately, or give any advice/comments on how to proceed?

You're doing it right. You can treat p as an array unsigned char[sizeof(double)] now.

For example:

for (int i = 0; i != sizeof(double); ++i)  printf("%02X ", p[i]);

For d = 0.125 this prints 00 00 00 00 00 00 C0 3F . Reversing endianness and decomposing into parts, this is:

00111111 11000000 0 0 0 0 0 0
   3F       C0    0 0 0 0 0 0

0   01111111100   0...<52 times>...0
S     Exponent         Mantissa
+     1023 - 3           1.0

The exponent field's value is 1020, which gives an exponent of −3 after correcting by the bias of 1023, and the mantissa is 1.0, after including the implicit leading 1. So the value is 2 −3 = 1/8.

If your motivation is only accuracy, use printf("%a\\n", d);

It displays the same information as going to the binary representation would, but it displays it in a format that's almost human-readable. Here (that is, for d=2; ), it displays 0x1p+1 . The number after 0x is the mantissa, normalized between 1 and 2, and in hexadecimal. The number after p is the exponent. It is displayed in decimal but it represents a power of two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM