Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the byte value of double from memory

Tags:

c++

double

byte

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?

like image 637
nf313743 Avatar asked Sep 03 '25 05:09

nf313743


2 Answers

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.

like image 126
Kerrek SB Avatar answered Sep 04 '25 20:09

Kerrek SB


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.

like image 39
Pascal Cuoq Avatar answered Sep 04 '25 19:09

Pascal Cuoq