how to understand the default format of cout - c++

I hope this is not a naive question. Is type conversion performed implicitly in c++? Because I have asked user to input a number in hexadecimal format, and then when i output that number to the screen without mentioning its format, it is displayed as a decimal format. Am I missing something here?
#include <iostream>
#include <iomanip> using namespace std;
int main() { int number = 0;
cout << "\nEnter a hexadecimal number: " << endl;
cin >> hex >> number;
cout << "Your decimal input: " << number << endl; number;
}

There's no type conversion between hexadecimal and decimal here. Internally your number will be stored in two's complimentary (a binary representation) no matter whether it has been read in as a hex or decimal number. Converting from a string of dec/hex to an integer and the other way around happens when the number is inputted/outputted.
With std::hex you tell the stream you tell the stream to change its default numeric base for integer I/O. Without it, the default is decimal. So if you only do it for std::cin, then it is reading in numbers as hex, but std::cout is still outputting decimal numbers. If you want it to also change its base to hexadecimal, you have to do the same with std::cout:
std::cout << std::hex << "Your hexadecimal input: " << number << std::endl;

Related

concatenating a Hexadecimal number with zeros

I have written a simple code to convert a fractional number to 24bit (3 bytes, 6 characters) Hexadecimal number.
Lets say if you enter 0.5, it provides the hexadecimal number as 0x400000.
0.1 = 0xccccd
0.001 = 0x20c5
While the answers are correct, What I'd like to do is preserve the 6 character representation, so i'd like 0.1 to be = 0x0ccccd and
0.001 to be = 0x0020c5.
I thought one possible method would be to convert the hexadecimal result to string and then use strlen to check number of digits and then concatenate the result with the appropriate zeros. The problem I have with this method is I'm not sure how to store the hex result in a variable.
I figured even if I convert the Hex number to string and find the number of zeros to concatenate, the program would be a bit clunky. There just might be a simpler way to achieve what I want to do. I just don't know how.
Hoping someone can show me the way forward. The program I wrote is below.
while(true){
float frac_no;
std::cout << "Enter a fractional number(0-1) or press 0 to exit:";
std::cin >> frac_no;
if(!frac_no){
break;
}
const int max_limit_24 = exp2(23); // The maximum value of 0x7FFFFF(1.0)
float inter_hex;
inter_hex = round(max_limit_24*frac_no);
int int_inter_hex = int(inter_hex);
std::cout << std::hex << "0x" << int_inter_hex << "\n" ;
}
#include <iomanip>
int val = 0x20c5;
std::cout << "0x" << std::setw(6) << std::hex << std::setfill('0') << val << '\n';
If you just need it to have the leading 0s on output. If you do want to store it as a string, you can use an std::stringstream instead of std::cout and get the string from it.

How to format doubles in the following way?

I am using C++ and I would like to format doubles in the following obvious way. I have tried playing with 'fixed' and 'scientific' using stringstream, but I am unable to achieve this desired output.
double d = -5; // print "-5"
double d = 1000000000; // print "1000000000"
double d = 3.14; // print "3.14"
double d = 0.00000000001; // print "0.00000000001"
// Floating point error is acceptable:
double d = 10000000000000001; // print "10000000000000000"
As requested, here are the things I've tried:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
string obvious_format_attempt1( double d )
{
stringstream ss;
ss.precision(15);
ss << d;
return ss.str();
}
string obvious_format_attempt2( double d )
{
stringstream ss;
ss.precision(15);
ss << fixed;
ss << d;
return ss.str();
}
int main(int argc, char *argv[])
{
cout << "Attempt #1" << endl;
cout << obvious_format_attempt1(-5) << endl;
cout << obvious_format_attempt1(1000000000) << endl;
cout << obvious_format_attempt1(3.14) << endl;
cout << obvious_format_attempt1(0.00000000001) << endl;
cout << obvious_format_attempt1(10000000000000001) << endl;
cout << endl << "Attempt #2" << endl;
cout << obvious_format_attempt2(-5) << endl;
cout << obvious_format_attempt2(1000000000) << endl;
cout << obvious_format_attempt2(3.14) << endl;
cout << obvious_format_attempt2(0.00000000001) << endl;
cout << obvious_format_attempt2(10000000000000001) << endl;
return 0;
}
That prints the following:
Attempt #1
-5
1000000000
3.14
1e-11
1e+16
Attempt #2
-5.000000000000000
1000000000.000000000000000
3.140000000000000
0.000000000010000
10000000000000000.000000000000000
There is no way for a program to KNOW how to format the numbers in the way that you are describing, unless you write some code to analyze the numbers in some way - and even that can be quite hard.
What is required here is knowing the input format in your source code, and that's lost as soon as the compiler converts the decimal input source code into binary form to store in the executable file.
One alternative that may work is to output to a stringstream, and then from that modify the output to strip trailing zeros. Something like this:
string obvious_format_attempt2( double d )
{
stringstream ss;
ss.precision(15);
ss << fixed;
ss << d;
string res = ss.str();
// Do we have a dot?
if ((string::size_type pos = res.rfind('.')) != string::npos)
{
while(pos > 0 && (res[pos] == '0' || res[pos] == '.')
{
pos--;
}
res = res.substr(pos);
}
return res;
}
I haven't actually tired it, but as a rough sketch, it should work. Caveats are that if you have something like 0.1, it may well print as 0.09999999999999285 or some such, becuase 0.1 can not be represented in exact form as a binary.
Formatting binary floating-point numbers accurately is quite tricky and was traditionally wrong. A pair of papers published in 1990 in the same journal settled that decimal values converted to binary floating-point numbers and back can have their values restored assuming they don't use more decimal digits than a specific constraint (in C++ represented using std::numeric_limits<T>::digits10 for the appropriate type T):
Clinger's "How to read floating-point numbers accurately" describes an algorithm to convert from a decimal representation to a binary floating-point.
Steele/White's "How to print floating-point numbers accurately" describes how to convert from a binary floating-point to a decimal decimal value. Interestingly, the algorithm even converts to the shortest such decimal value.
At the time these papers were published the C formatting directives for binary floating points ("%f", "%e", and "%g") were well established and they didn't get changed to the take the new results into account. The problem with the specification of these formatting directives is that "%f" assumes to count the digits after the decimal point and there is no format specifier asking to format numbers with a certain number of digits but not necessarily starting to count at the decimal point (e.g., to format with a decimal point but potentially having many leading zeros).
The format specifiers are still not improved, e.g., to include another one for non-scientific notation possibly involving many zeros, for that matter. Effectively, the power of the Steele/White's algorithm isn't fully exposed. The C++ formatting, sadly, didn't improve over the situation and just delegates the semantics to the C formatting directives.
The approach of not setting std::ios_base::fixed and using a precision of std::numeric_limits<double>::digits10 is the closest approximation of floating-point formatting the C and C++ standard libraries offer. The exact format requested could be obtained by getting the digits using using formatting with std::ios_base::scientific, parsing the result, and rewriting the digits afterwards. To give this process a nice stream-like interface it could be encapsulated with a std::num_put<char> facet.
An alternative could be the use of Double-Conversion. This implementation uses an improved (faster) algorithm for the conversion. It also exposes interfaces to get the digits in some form although not directly as a character sequence if I recall correctly.
You can't do what you want to do, because decimal numbers are not representable exactly in floating point format. In otherwords, double can't precisely hold 3.14 exactly, it stores everything as fractions of powers of 2, so it stores it as something like 3 + 9175/65536 or thereabouts (do it on your calculator and you'll get 3.1399993896484375. (I realize that 65536 is not the right denominator for IEEE double, but the gist of it is correct).
This is known as the round trip problem. You can't reliable do
double x = 3.14;
cout << magic << x;
and get "3.14"
If you must solve the round-trip problem, then don't use floating point. Use a custom "decimal" class, or use a string to hold the value.
Here's a decimal class you could use:
https://stackoverflow.com/a/15320495/364818
I am using C++ and I would like to format doubles in the following obvious way.
Based on your samples, I assume you want
Fixed rather than scientific notation,
A reasonable (but not excessive) amount of precision (this is for user display, so a small bit of rounding is okay),
Trailing zeros truncated, and
Decimal point truncated as well if the number looks like an integer.
The following function does just that:
#include <cmath>
#include <iomanip>
#include <sstream>
#include <string>
std::string fixed_precision_string (double num) {
// Magic numbers
static const int prec_limit = 14; // Change to 15 if you wish
static const double log10_fuzz = 1e-15; // In case log10 is slightly off
static const char decimal_pt = '.'; // Better: use std::locale
if (num == 0.0) {
return "0";
}
std::string result;
if (num < 0.0) {
result = '-';
num = -num;
}
int ndigs = int(std::log10(num) + log10_fuzz);
std::stringstream ss;
if (ndigs >= prec_limit) {
ss << std::fixed
<< std::setprecision(0)
<< num;
result += ss.str();
}
else {
ss << std::fixed
<< std::setprecision(prec_limit-ndigs)
<< num;
result += ss.str();
auto last_non_zero = result.find_last_not_of('0');
if (result[last_non_zero] == decimal_pt) {
result.erase(last_non_zero);
}
else if (last_non_zero+1 < result.length()) {
result.erase(last_non_zero+1);
}
}
return result;
}
If you are using a computer that uses IEEE floating point, changing prec_limit to 16 is unadvisable. While this will let you properly print 0.9999999999999999 as such, it also prints 5.1 as 5.0999999999999996 and 9.99999998 as 9.9999999800000001. This is from my computer, your results may vary due to a different library.
Changing prec_limit to 15 is okay, but it still leads to numbers that don't print "correctly". The value specified (14) works nicely so long as you aren't trying to print 1.0-1e-15.
You could do even better, but that might require discarding the standard library (see Dietmar Kühl's answer).

How to convert binary into decimal using <bitset> library?

I use this simple code to convert a decimal into binary :
#include <iostream>
#include <windows.h>
#include <bitset>
using namespace std;
int main(int argc, char const *argv[]){
unsigned int n;
cout << "# Decimal: "; cin >> n; cout << endl;
bitset<16>binary(n);
cout << endl << "# Binary: " << binary << endl;
system("Pause"); return 0;
}
How to convert "binary" into decimal and assign the value to other variable ?
n is not "a decimal". I think you have a misconception of what numbers are, based on the default output representation used by IOStreams. They are numbers. Not decimal strings, binary strings, hexadecimal strings, octal strings, base-64 strings, or any kind of strings. But numbers.
The way you choose to represent them on output is entirely orthogonal to the way they are stored internally (which is, actually, base-2 not decimal), so it is highly likely that these "conversions" you're trying to do are inappropriate.
However, if you wish to extract an integer from a std::bitset instance, you may do so using the to_ulong() member function.
Get into the habit of using the documentation.

Why does cout truncate a double?

The following is my console input/output.
Please enter a real number: -23486.33
Characters checked: 9
Thank you.
The real number you entered is -23486.3
The value I entered is -23486.33, but yet cout prints it as -23486.3.
The relevant code is below:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function prototype (declaration)
string readDouble();
bool isValidDouble(string);
int main()
{
string value;
double number;
value = readDouble();
while (!isValidDouble(value)) {
cout << "The number you entered is not a valid integer." << endl;
value = readDouble();
}
number = atof(value.c_str());
cout << "Thank you." << endl
<< "The real number you entered is " << number << endl;
}
When debugging, I check the value of number right after the method call atof(value.c_str())l;. Number is shown to have a value of -23486.33. So what happens between that and the print out by cout? In no part of my code do I set the precision of cout or make it fixed.
If you have any questions, please let me know.
Have you tried
std::cout << std::setprecision(2) << number;
look at:
http://www.cplusplus.com/reference/iomanip/setprecision/
-23486.3 is displayed because std::cout prints only 6 digits by default.
To print back a number entered from standard input (convertion text → floating number → text), you can use set_precision with digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.33
To print a number with full precision (usually for convertion floating number → text → floating number), you can use set_precision with max_digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.330000000002
Here the printed number is not the same because -23486.33 doesn't have an exact representation in IEEE encoding (expressed in base 2 instead of base 10).
For more details with digits10 and max_digits10, you can read:
difference explained by stackoverflow
digits10
max_digits10
Set a precision when you output a double and keep precision explicitly when you compare them.
When you convert a string presentation of a DEC number to a double(float point number presentation), the data in the memory might not be mathematically equal to the string presentation. It's the best approximation by a float point number presentation, and vise versa.
You can set the precision to the maximum limit for double.
The code snippet is here:
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
double number = ... // your double value.
cout << setprecision(numeric_limits<double>::digits10) << number << endl;

Display a number decimal format instead as an exponential in cout

I calculated a total of floats and I got a number like 509990e-405. I'm assuming this is the short version; how can I cout this as a full number?
cout << NASATotal << endl;
is what I have now.
You can force the output to be not in scientific notation, and to have the sufficient precision to show your small number.
#include <iomanip>
// ...
long double d = 509990e-405L;
std::cout << std::fixed << std::setprecision(410) << d << std::endl;
Output:
0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000050999000000
If you really want this is another question.
You can write your own BigNumber class that stores the results as strings. You would have to implement all of your numeric operations and I'm guessing performance will be an issue. But it can be done, no problem -- assuming that is what you want.