473,725 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
+ 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 7999
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_c ast<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
5800
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 is there an easier way? Is there some handy functions which do this? example. File contains: 42 7C 00 00 I want to read it in and end up with my C variable equalling 63.
4
11583
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; myIntVal = CStringToBinary(myVal);
1
3948
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 I can get around everything but one stumbling point I would like some advice on. The win api uses an unsigned char array for writing binary data to and from the gds file. Now, one reason I want standards compliant code is to be able to run my...
8
9528
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 contains the following three floating-point numbers: 1.0 2.0 3.0
25
3644
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 -- comp.lang.c.moderated - moderation address: clcm@plethora.net
6
2253
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
19222
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 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
11
3591
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 Read_bin(ByVal ruta As String) Dim cadena As String = "" Dim dato As Array If File.Exists(ruta) = True Then
5
6638
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 an unsigned short int is 16-bits). For example, the double precision representation of 1/3 is 3fd5 5555 5555 5555 (hex).
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4519
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.