473,725 Members | 2,193 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

More of a raw kind of cast


Before I begin, here's a list of assumptions for this particular example:

(1) unsigned int has no padding bits, and therefore no invalid bit-
patterns or trap representations .
(2) All types have the same alignment requirements.
(3) sizeof(double) >= sizeof(unsigned )

=============== =============== =======

We can cast from double to unsigned int as follows:

int main()
{
double d = 672.23;

unsigned i = d;
}
However, if we want a raw kind of cast, i.e. simply access the double's
data in memory as if it were an unsigned int, then we can write:

int main()
{
double d = 672.23;

unsigned i = *reinterpret_ca st<unsigned*>( &d );
}

However, my question is this:

Do we have to bother with pointers as in the previous snippet, or can
we use references?

int main()
{
double d = 672.23;

unsigned i = reinterpret_cas t<unsigned&>( d );
}

--

Frederick Gotham
Jun 29 '06 #1
5 2365
On Thu, 29 Jun 2006 19:15:52 GMT, Frederick Gotham
<fg*******@SPAM .com> wrote in comp.lang.c++:

Before I begin, here's a list of assumptions for this particular example:

(1) unsigned int has no padding bits, and therefore no invalid bit-
patterns or trap representations .
(2) All types have the same alignment requirements.
(3) sizeof(double) >= sizeof(unsigned )

=============== =============== =======

We can cast from double to unsigned int as follows:
No, you can't. A cast is ONLY performed by a cast operator, either
the original C cast, or one of the new cast operators defined in C++.
int main()
{
double d = 672.23;

unsigned i = d;
}
The code above performs a conversion, specifically an automatic
conversion on assignment. There is no cast involved. A cast is an
EXPLICIT conversion, defined as such by both C and C++. Some
conversions occur automatically in expressions, others require a cast
operator.

We CAN cast from double to unsigned like this:

int main()
{
double d = 672.23;
unsigned i = (double)d; // other C++ casts could be used
}

This shows that you can use a cast operator to specifically perform a
conversion that would occur automatically in the expression anyway.
However, if we want a raw kind of cast, i.e. simply access the double's
data in memory as if it were an unsigned int, then we can write:
This is not a cast either. What you are doing is trying to access the
raw underlying bits of an object, with an lvalue of a different type.
int main()
{
double d = 672.23;

unsigned i = *reinterpret_ca st<unsigned*>( &d );
}

However, my question is this:

Do we have to bother with pointers as in the previous snippet, or can
we use references?
First, the answer is no.

Second, you are not actually having to "bother with pointers", you are
bothering with addresses, which is the name of the type of value held
by a pointer.

The unary '&' operator generates the address of its operand. The cast
takes that address rvalue, which has the type "address of double", and
convert it to an rvalue which has the type "address of unsigned int".
Most likely, there is no change in the bitwise representation of the
address, merely in the number of bits read from memory during the
lvalue to rvalue conversion and how they are interpreted.

No actual pointer exists or is created.
int main()
{
double d = 672.23;

unsigned i = reinterpret_cas t<unsigned&>( d );
}


This is trying to cast a double to a reference to int, which quite
impossible.

I don't know what you think the overhead of the pointer cast is. You
are only changing how the address is used to access memory, not
actually create a pointer.

Consider this variation on your second and third examples:

int main()
{
double d1 = 672.23, d2 = 666.89;
unsigned i1 = d1;
unsigned i2 = *reinterpret_ca st<unsigned*>(& d2);
}

Do you think the compiler will generate more machine instructions for
the second than it does for the first?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jun 29 '06 #2
Jack Klein posted:

What you are doing is trying to access the raw underlying bits of an
object, with an lvalue of a different type.

Indeed.

My question is very simple. If we have an object like as follows:

double d;

Then are the following two expressions equivalent?

(1) *reinterpret_ca st<unsigned*>( &d )

(2) reinterpret_cas t<unsigned&>( d )

--

Frederick Gotham
Jun 29 '06 #3
Frederick Gotham wrote:
...
My question is very simple. If we have an object like as follows:

double d;

Then are the following two expressions equivalent?

(1) *reinterpret_ca st<unsigned*>( &d )

(2) reinterpret_cas t<unsigned&>( d )
...


Yes, they are. The equivalence of the two is explicitly stated in 5.2.10/10.

I don't know why Jack is saying that the second one is an attempt to
cast a 'double' value to reference type. When an lvalue is used as an
argument for an 'reinterpret_ca st' to reference type, the argument is
interpreted as a "reference" value (as a 'double&' in your example, not
as a 'double' rvalue), which is then converted to the target reference type.

--
Best regards,
Andrey Tarasevich
Jun 29 '06 #4
Jack Klein wrote:
On Thu, 29 Jun 2006 19:15:52 GMT, Frederick Gotham
<fg*******@SPAM .com> wrote in comp.lang.c++:
int main()
{
double d = 672.23;

unsigned i = d;
}


The code above performs a conversion, specifically an automatic
conversion on assignment.


Surely you mean on initialization?

Luke

Jun 30 '06 #5
Luke Meyers posted:
Jack Klein wrote:
On Thu, 29 Jun 2006 19:15:52 GMT, Frederick Gotham
<fg*******@SPAM .com> wrote in comp.lang.c++:
> int main()
> {
> double d = 672.23;
>
> unsigned i = d;
> }


The code above performs a conversion, specifically an automatic
conversion on assignment.


Surely you mean on initialization?

Indeed I do.

However we're dealing with intrinsic POD's, so there's no difference.

Notheless, yes, I should have said "initialisation ".
--

Frederick Gotham
Jun 30 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

303
17689
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
24
3073
by: Kari Laitinen | last post by:
I have written a computer programming book that uses C++. The book is for beginners in the field of computer programming, but it might give useful ideas also for more experienced programmers. Computer programs are presented in a very easy-to-read way in my book. To find out what that exactly means, please read the pages at http://www.naturalprogramming.com/cppbook.html There you can find free sample pages for printing and other
2
2891
by: STB | last post by:
ciao a tutti... ci risono... devo migliorare delle performance di accesso ad una tabella... la tabella non ha indice primario, ne altri indici... sulla tabella ci accedo con select di questo tipo.. select @ExistInOAG = count(*) FROM caprs05dev.dbo.OAG WHERE Air_Carrier = @Aircarrier and cast(ltrim(rtrim(Flt_nbr)) as int) =
3
2300
by: Lionel B | last post by:
In an overloaded output operator for a class I want to detect ostream manipulators such as flush, endl, ends, etc. I am stymied by how to do this; here's a minimal program indicating my problem: // test.cpp #include <iostream> void foo(std::ostream& (*f)(std::ostream&)) { if (f == &std::endl) std::cout << "Detected 'endl'\n"; // line 5
0
3590
by: Aaron W. West | last post by:
Fun with CAST! (Optimized SQLServerCentral script posts) I found some interesting "tricks" to convert binary to hexadecimal and back, which allow doing 4 or 8 at a time. Test code first: -- These two have the same output, other than the width: select dbo.ufn_vbintohexstr(0x123456789abcdef1234) select 0x123456789abcdef1234
7
9145
by: ma740988 | last post by:
Consider: # include <iostream> # include <string> # include <map> # include <bitset> # include <vector> using namespace std;
17
2417
by: Chen Shusheng | last post by:
Hi all, In fact, I want to let my memory run out. And see what will happen. My system is windowsXp. Memory is 256M.I think my cdes will apply more memory than I have. Codes are below: #include <stdlib.h> #include<stdio.h> #define MAX 1000000000
13
2846
by: David | last post by:
Hi all, I have a singleton ienumerable that collects data from a database. I have listed the code below. It has the usual methods of current, move and reset. I need to go to a certain position or set filters or many other things and I don't know how to do this. I have just learned singleton AND ienumerable, so miraculously got this to work so far. I could do with a bit of help to go further with it. If need by, I may have to change the...
1
2243
by: Aleck | last post by:
Hie. I have a trigger that monitors changes to my table fields but I get an error saying subquery returned more than one value.Below is the code for my trigger, hope you will figure out whats happening.. CREATE TRIGGER trgmyTableAuditFields ON myTable WITH ENCRYPTION FOR INSERT, UPDATE, DELETE AS BEGIN
0
8888
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
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
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...
1
6702
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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?
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.