473,473 Members | 1,511 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

binary representation of double, conversion of double to unsigned char and int

25 New Member
I am a newbie and have been trying to understand conversion from double to int and then back to int using the following code was posted on the c++ google group. Could someone help me out with understanding why and how a double can be represented in bits and bytes and which of the following can allow us to view the binary representation, unsigned char representation and then convert back to int please...

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<iomanip>
  3. #include <bitset>
  4. #include <limits> 
  5. using namespace std;
  6.  
  7. union
  8. {
  9.     double d;
  10.     char c[sizeof(double)];
  11. } conv;
  12.  
  13. int main()
  14. {
  15.     // int to float can be done has *(reinterpret_cast<float *>(&intValue));
  16.     int i = 3;
  17.     float f = 4.34;
  18.     f = *(reinterpret_cast<float *>(&i));
  19.     cout << f << endl;
  20.     cout << static_cast<int>(f) << endl;
  21.  
  22.     // TO STORE VALUES
  23.     //I. double (8 bytes) conversion to a float (4 bytes)
  24.     double n = 3221.12332;        
  25.     long n2 = *(reinterpret_cast<long*>(&n));
  26.     long n3 = *(reinterpret_cast<long*>(&n) + 1); 
  27.  
  28.     // DOES NOT WORK
  29.     //II. using unions to get the bit representation of a double 
  30.     conv.d = 32;
  31.     // print out double in hex
  32.     for (int i =0; i < sizeof(double); ++i)
  33.         cout << hex << setfill('0') << setw(2) << conv.c[i]; 
  34.     cout << endl;
  35.  
  36.     // DOES NOT WORK 
  37.     //III. any object can be considered as a sequence of unsigned chars
  38.     double d = 999;
  39.     unsigned char *p=reinterpret_cast<unsigned char *>(&d);
  40.     for(unsigned i=0; i<sizeof(d); ++i)
  41.        cout<<static_cast<unsigned>(p[i])<<" ";
  42.     cout<<endl;
  43.  
  44.     //IV. DONT KNOW IF IT WORKS
  45.     double d1 = 1000;
  46.     unsigned char *p1=reinterpret_cast<unsigned char *>(&d1);
  47.     // There are systems where 1 byte is more than 8 bits
  48.     bitset<numeric_limits<unsigned char>::digits> byte;
  49.     for(unsigned i=0; i<sizeof(d1); ++i)
  50.     {
  51.         byte = p1[i];
  52.         for(unsigned j=0; j<byte.size(); ++j)
  53.              cout << byte[j];
  54.     }
  55.  
  56.     // how do we convert to an int and see the same value as that of double
  57.     unsigned long long int x;
  58.     x = *(reinterpret_cast<int *>(&d1));
  59.     cout << "int x: " << x << endl;
  60.  
  61.     cout<<endl;
  62.  
  63.     system("pause");
  64.     return 0;       
  65. }
Oct 5 '07 #1
1 7929
weaknessforcats
9,208 Recognized Expert Moderator Expert
First: Do not cast in C++. It's a bad habit.

Second: Read up on Aritmetic Conversions. An int can be converted to a double with .0 for a decimal. But the double can never be converted back to an int without truncating the decimal and losing data. Your compiler will bark at you about this.

The general rule is: Do not mix integer and floating point. Stick with one or the other.

Floating point is slow, has automatic rounding and limited accuracy and is intended for scientific use only where extreme accuracy is not required. If you have to use floating point, use double thoughout unless you can write a real reason down on paper as to why this won't work.

In the integer family, any integer (and char is an integer- there are no characters in C or C++) can be freely copied to any other integer with you being responsible that you don't lose data.

This code:
float f = 4.34;
has a bug in it. 4.34 is a double. f is a float. A float is smaller than a double so you get warnings here about truncation an possible loss of data. The correct code is:
Expand|Select|Wrap|Line Numbers
  1.  double f = 4.34;
  2.  
because you aren't supposed to use float. If you insist, then at least tell the compiler to create the constant as a float:
Expand|Select|Wrap|Line Numbers
  1.   float f = 4.34F;   /or 4.34f
  2.  
This is utter garbage:
f = *(reinterpret_cast<float *>(&i));
&i is the address of an int. Forcing the compiler to accept as the address of a float is just illogical. Then, after that you assign the bits in the int to the float when the arrangement of he bits in the int do not conform to IEEE754.

f is now corrupted.

Nothing after this can be analyzed.
Oct 6 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

13
by: E-Star | last post by:
I have a binary file that I want to read some numbers out of. However the numbers are 32bit floats. How can I get the numbers into a C program to use? I can do the calculations manually....but...
4
by: Delali Dzirasa | last post by:
Does anyone know of the fastest way to convert a CString of numbers ie "00000001" to the binary representation in an int? for example CString myVal = "00000001"; int myIntVal = 0; ...
1
by: glen_stark | last post by:
Hi. I have code for reading and writing gds files that I have inherited from a company and need to make standards compliant. Unfortunately the code is heavily dependant on the win api. I think...
8
by: Yeow | last post by:
hello, i was trying to use the fread function on SunOS and ran into some trouble. i made a simple test as follows: i'm trying to read in a binary file (generated from a fortran code) that...
25
by: Gaurav Verma | last post by:
Hi, I want to convert a floating point number (or a decimal number say 123.456) into binary notation using a C program. Can somebody help me out with it? Thanks Gaurav --...
6
by: alice | last post by:
hi all, Can anybody please tell the advantages which the binary files offers over the character files. Thanks, Alice walls
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
11
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function...
5
by: anders.weitman | last post by:
Hi! I want to get the representation in memory of a variable of type double and put it in an array of four unsigned short int (I'm on a 32- bits Windows architecture so a double is 64-bits and...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.