Botan  2.7.0
Crypto and TLS for C++11
big_io.cpp
Go to the documentation of this file.
1 /*
2 * BigInt Input/Output
3 * (C) 1999-2007 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #include <botan/bigint.h>
9 #include <istream>
10 #include <ostream>
11 
12 namespace Botan {
13 
14 /*
15 * Write the BigInt into a stream
16 */
17 std::ostream& operator<<(std::ostream& stream, const BigInt& n)
18  {
20  if(stream.flags() & std::ios::hex)
21  base = BigInt::Hexadecimal;
22  else if(stream.flags() & std::ios::oct)
23  throw Exception("Octal output of BigInt not supported");
24 
25  if(n == 0)
26  stream.write("0", 1);
27  else
28  {
29  if(n < 0)
30  stream.write("-", 1);
31  const std::vector<uint8_t> buffer = BigInt::encode(n, base);
32  size_t skip = 0;
33  while(skip < buffer.size() && buffer[skip] == '0')
34  ++skip;
35  stream.write(cast_uint8_ptr_to_char(buffer.data()) + skip,
36  buffer.size() - skip);
37  }
38  if(!stream.good())
39  throw Stream_IO_Error("BigInt output operator has failed");
40  return stream;
41  }
42 
43 /*
44 * Read the BigInt from a stream
45 */
46 std::istream& operator>>(std::istream& stream, BigInt& n)
47  {
48  std::string str;
49  std::getline(stream, str);
50  if(stream.bad() || (stream.fail() && !stream.eof()))
51  throw Stream_IO_Error("BigInt input operator has failed");
52  n = BigInt(str);
53  return stream;
54  }
55 
56 }
int operator<<(int fd, Pipe &pipe)
Definition: fd_unix.cpp:17
Definition: alg_id.cpp:13
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition: mem_ops.h:136
int operator>>(int fd, Pipe &pipe)
Definition: fd_unix.cpp:40
static std::vector< uint8_t > encode(const BigInt &n, Base base=Binary)
Definition: big_code.cpp:54