How do you convert between Primitive Data Types?

Started by
4 comments, last by swiftcoder 9 years ago

Hello

How do you convert between primitive data types (limited only to STL) and why do you use that methodology/methodologies?

In my work environment we stick strictly to STL and typically use StringStream to convert between primitive data types. I am looking to hear how you do it and also for advice on more efficient/better methodologies to perform this conversion as I've heard StringStream can be slow? I am going to get into Embedded C++ so these expensive conversions will really start to matter.

I'm aware of atoi, atof, etc. but these only work for c strings apparently. Thanks in advance for your advice and feedback.

Advertisement
Primitive data types? This is what I do:


double d = 5.0;
float f = (float)d;
int i = (int)d;
If you're talking about something else, please use correct terminology.

If you had posted this in "For Beginners" I would have responded very differently, but in "general programming" coupled with a statement that you are a professional...

This is 2015. C++ has been standardized for nearly two decades.

Unless you are a professional programmer working in an atypical environment, "STL" is not what what you use. It is the "c++ standard library", or "the standard libraries".

STL typically either meant HP's libraries or SGI's libraries primarily used in-house. Hence, SGI's standard libraries were standard at SGI, HP's standard libraries were standard at HP, and neither were standard in the early days of C++. Both had parts of their libraries incorporated to the C++ standard library in the early 1990s. A lot of hard work went into standardizing the language in the mid 1990s, and in 1998 the c++ language was standardized, including a collection of routines called "the c++ standard library". Unfortunately some bad tutorials and books refer to the C++ standard library as "STL". Please don't do that. For two decades we use the C++ Standard Library, not the STL.

Since then the language has gone through five major updates, but those old tutorials and bad websites keep calling the standard library the "STL".


typically use StringStream to convert between primitive data types

Correct names are important.

Please be careful of your words. This is a technical forum and programming languages have precise definitions of terms. Using the wrong words leads to confusion and errors.

The class is often used to perform what is called a lexical cast. That is, to convert between a numeric value and text forms. Such as converting the string "1234" into the integer value 1234, or back again.

Like the form:


stringstream intermediate; 
intermediate << str; 
intermediate >> number;
In addition to that type of lexical cast, there are other types of casts and conversions.

Integral promotions are conversions that start at bool move up the chain of signed char, unsigned char, short, unsigned short, int, unsigned int, long int, unsigned long int, long long int, and unsigned long long int. Floating point promotions are conversions that move from float to double.

Because these conversions always expand the size and have room to store the underlying data they are done automatically, called implicit conversions.

If you go the other way down the chain, moving from a bigger type to a smaller type, you need to do an explicit conversion, using a cast. There are several explicit conversion casts you can choose between. One is the c-style cast like Nypyren suggested, where the destination type is in parenthesis. (int)myLongLong. There is a similar version that does exactly the same thing in C++: static_cast<int>(myLongLong).

I don't know about you, your company, your project, or your code base. Generally when working with existing code it is good to stay uniform with the existing practice. If you are doing new development you can pick up different practices and patterns.

Again, these are technical forums, and technical language means using the correct terms wherever possible. This includes terms like "STL" versus "Standard Library" and names of the types of conversions and casts.

As written, your post is unclear due to the poor choice of words.

Continuing with your post:


I've heard StringStream can be slow
Be careful about hearing generically that something can be slow. Sometimes things are slow in one context, and fast in another. Sometimes things that used to be fast or were fast on certain systems are slow today. And sometimes things that used to be slow have become extremely fast.

Yes, relative to most other kinds of conversion, using stringstream as a lexical cast is relatively slow. It has a lot of complex parts. It needs memory buffers, and it does many different validations.

However, speed is relative. It may not be slow in your situation.

If you do something only once and it is not in a time critical section, speed is completely irrelevant.

If you do something a large number of times within a time critical section, speed becomes a factor.

If you do something millions of times with a large volume of data, speed becomes a factor.

STL typically either meant HP's libraries or SGI's libraries primarily used in-house.


Ok, I agree with the terminology sentiment for the most part, but this is off base. "STL" is still a very commonly used term (even by various members of the C++ committee and by compiler and stdlib implementors).

Microsoft calls it the STL
cpluplus.com still calls it the STL
Scott Meyers has a whole series of old but popular books with STL in the title

STL is not the _official_ term, but it's perfectly obvious what it refers to.

Again, the OP was rather unclear, but it wasn't the term "STL" that made it so.

Sean Middleditch – Game Systems Engineer – Join my team!

You mentioned embedded programming. A lot of embedded systems work with very old or very limited C++ environments, so I'll go over both the modern shiny new ways of doing this, the older ways that your system supports, and the low-level hacky embedded programmer ways they might be done.

In my work environment we stick strictly to STL and typically use StringStream to convert between primitive data types. I am looking to hear how you do it and also for advice on more efficient/better methodologies to perform this conversion as I've heard StringStream can be slow?

I'm aware of atoi, atof, etc. but these only work for c strings apparently. Thanks in advance for your advice and feedback.


Modern C++ provides in the <string> header several sets of functions for converting between primitive numeric types and std::string:

std::to_string is an overloaded function that converts a value into a std::string, unsurprisingly.
std::stoi - and its cohorts stol, stod, stof, etc. - do the reverse and convert a std::string into a primitive type.

See http://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c for a more thorough explanation and more links.

These facilities can be problematic for embedded developers or game developers, though. First, they're only supported on newer C++ implementations. Second, they all require marshalling your strings through std::string which in turns require copies and allocations if you're moving the data back and forth between network buffers or the like. Third, they rely on exceptions as their error mechanism.

The older methods for C++ are exactly what you describe. The performance isn't great, but it's not "bad" unless you are measuring an actual problem. If you're only formatting a handful of strings for debug purposes every once in a while, who cares if the C++ IOStreams stuff is slow? If you're unsure if there might be a problem down the road, encapsulate all of your string formatting/conversion behind some functions and then you can freely optimize the code without requiring any rewrites.

To avoid all of these issues you can use the C library equivalents. The above will often just wrap around the C versions anyway, so the C versions will generally be as fast or faster just by that fact alone.

You can easily use C++ strings with C libraries in most cases. You can grab a C string from a std::string using the .c_str() method, and you can do the same for a string_buf (stringstream) as well.

Simply writing your own conversions for integral types (bool, int, long, signed and unsigned, etc.) is quite easy, though it should be your absolute last resort. Writing your own conversion routine for floating-point types is about one step short of impossible that nobody other than a real computational scientist with years of IEEE754 study should even attempt; thankfully, there's free code online written by such masters, should you need it. In general, I'd recommend sticking to the C++ facilities first and the C facilities after that and only doing it manually if you _really_ need something special.

Some embedded systems will supply their own very high performance conversion routines. There's even a handful that have direct hardware support and intrinsics for such conversions, but it's rather unlikely you're working with any of those (I don't know of any in mass production). Even without hardware support, a chip vendor may have some hardware considerations that led to them writing their own non-standard libraries. Check your embedded platform's documentation.

While you said you want to stick to the STL, do keep in mind that there are other formatting libraries out there. cppformat is great for generating formatted strings and is quite speedy and efficient, plus it includes helper routines for the simpler primitive type conversions. Boost has a lexical_cast<> library, though it's mostly superseded by the C++11 standard library additions (and Boost is almost a dirty word in many circles, especially in embedded and game programming).

Sean Middleditch – Game Systems Engineer – Join my team!

We may be thoroughly off-topic by this point, but I don't feel that it is unreasonable to advocate the use of accurate terminology on a technical subforum.

Microsoft calls it the STL

Microsoft only refers to the subset dealing specifically with containers and iterators as the STL. If you go one level up in their navigation, you will note that they correctly refer to the entirely as the 'C++ Standard Library'.

cpluplus.com still calls it the STL

While the URL does in fact still contain the text STL, I challenge you to find more than 3 mentions of it in the text of the site.

Scott Meyers has a whole series of old but popular books with STL in the title

Published in 2001, which IIRC, is before the term 'STL' fell out of use.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement