1 //  serialization.cpp : examples how to serialize posit values
2 //
3 // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
4 //
5 // This file is part of the universal numbers project, which is released under an MIT Open Source license.
6 
7 // configure the posit environment to print native posit format as default
8 #define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 1
9 #include <universal/number/posit/posit.hpp>
10 
main(int argc,char ** argv)11 int main(int argc, char** argv)
12 try {
13 	using namespace sw::universal;
14 
15 	int nrOfFailedTestCases = 0;
16 
17 	std::cout << "Lossless serialization of posit values\n";
18 
19 	constexpr size_t nbits = 40;
20 	constexpr size_t es    =  3;
21 	posit<nbits, es> a, b, c;
22 
23 	a =  1.23456789012345;
24 	b = -1.23456789012345;
25 	c = NAR;
26 
27 	// without the POSIT_ROUNDING_ERROR_FREE_IO_FORMAT flag set
28 	// the following statements would simply print the value of the posits.
29 	// Default ostream behavior of a posit
30 	//	a :  1.23457
31 	//	b : -1.23457
32 	//	c : -nan(ind)
33 	// Now they will print in native posit format.
34 	// Lossless serialization of posit values
35 	//	a : 40.3x40f03290a3p
36 	//	b : 40.3xbf0fcd6f5dp
37 	//	c : 40.3x8000000000p
38 	std::cout << "a : " << a << '\n';
39 	std::cout << "b : " << b << '\n';
40 	std::cout << "c : " << c << '\n';
41 
42 	// in addition to using a system-wide flag to modify ostream behavior
43 	// you can also print native posit format using an ostream helper
44 	std::cout << "Using an ostream helper\n";
45 	std::cout << "a : " << hex_format(a) << " a value : " << double(a) << '\n';
46 	std::cout << "b : " << hex_format(b) << " b value : " << double(b) << '\n';
47 	std::cout << "c : " << hex_format(c) << " c value : " << double(c) << '\n';
48 
49 	return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
50 }
51 catch (char const* msg) {
52 	std::cerr << msg << std::endl;
53 	return EXIT_FAILURE;
54 }
55 catch (...) {
56 	std::cerr << "Caught unknown exception" << std::endl;
57 	return EXIT_FAILURE;
58 }
59