convert 8 bytes into double and back?
 CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: convert 8 bytes into double and back?

#### Hybrid View

1. Junior Member
Join Date
Sep 2013
Posts
18

## convert 8 bytes into double and back?

I have a question. I receive a byte stream. The first 8 bytes contain an Identification number. I receive at first the lowest byte and at the end the highest byte of the number.
How can I transform this into a double value and later back into the bytestream? In the past I hard only 2 Byte values and there I could use things like MAKEWORD and HIBYTE and LOWBYTE to convert the values

2. Elite Member Power Poster
Join Date
Apr 2000
Location
Belgium (Europe)
Posts
4,626

## Re: convert 8 bytes into double and back?

if the 8 bytes represent an actualdouble in the double format...

1) use a Union of a double and an array of 8 bytes.
2) store the bytes in an 8 byte array, the copy the contents into a double with memcpy()
3) store in an array, then typecast the array pointer to a double pointer and dereference.
...

3. ## Re: convert 8 bytes into double and back?

The format of a double is described in
http://en.wikipedia.org/wiki/Double-...g-point_format

Basically there are 52 bits for the fraction part, 11 bits for the exponent and 1 bit for the sign. From the OP post #1, the 8 bytes represent an identification number which is probably an integer and not a floating point (double) number so a double number cannot be used correctly to store the id.

The type you probably need is long long or __int64 (both 8 byte integer).

4. ## Re: convert 8 bytes into double and back?

One possible way of obtaining the id as a long long is

Code:
```#include <stdio.h>

int main()
{
unsigned char id[] = {1,2,3,4,5,6,7,8};

long long res = 0;

for (int b = 0; b < 8; ++b)
res |= ((long long)id[b]) << (b * 8);

unsigned char *ares = (unsigned char*)&res;

for (int i = 0; i < 8; ++i)
printf("%02x ", ares[i]);

return 0;
}```

5. Junior Member
Join Date
Sep 2013
Posts
18

## Re: convert 8 bytes into double and back?

Thank you the last post is helping me. so far I created me this type for my 8 byte value:
typedef unsigned __int64 QWORD;

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•