Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Nov 6, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Changing the Endian-ness of a Number

Suppose you receive an int from a remote host and you wish to convert it to big-endian order. Here is another portable solution for handling of big and little endian data formatting. This solution is based on the use of the right shift operator:

// big endian
int to_big_endian(int d)
 unsigned char buffer[sizeof (int)];
 buffer [0] = (char) d >> 24;
 buffer [1] = (char) d >> 16;
 buffer [2] = (char) d >> 8;
 buffer [3] = (char) d;
 return * (int*)buffer;

To convert an int to little endian byte ordering, use the following function:

// little endian 
int to_little_endian(int d)
 buffer [0] = (char) d;
 buffer [1] = (char) d >> 8;
 buffer [2] = (char) d >> 16;
 buffer [3] = (char) d >> 24;
 return * (int*)buffer;

These functions may not generate the fastest code, but they are portable. Tip #684 Intermediate Reading Strings that Contain Whitespaces The std::getline() functions reads data from an input stream and writes it to a string object. Unlike cin's >> operator, getline() also reads whitespaces, which makes it useful for reading strings that contain blanks. For example:

#include <string>
#include <iostream>
int main()
 std::string name;
 cout<<"enter first name and last name: ";
 std::getline(std::cin, name);

getline() has three parameters, the third of which is a delimiter serving as a string terminator. By default, the delimiter's value is '\n'. You can override this value and define a different delimiter. For example, you can define the sign '\t' (tab) as the delimiter:

std::getline(cin, name, '\t');
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date