Botan  1.11.15
src/lib/math/bigint/big_io.cpp
Go to the documentation of this file.
00001 /*
00002 * BigInt Input/Output
00003 * (C) 1999-2007 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/bigint.h>
00009 #include <iostream>
00010 
00011 namespace Botan {
00012 
00013 /*
00014 * Write the BigInt into a stream
00015 */
00016 std::ostream& operator<<(std::ostream& stream, const BigInt& n)
00017    {
00018    BigInt::Base base = BigInt::Decimal;
00019    if(stream.flags() & std::ios::hex)
00020       base = BigInt::Hexadecimal;
00021    else if(stream.flags() & std::ios::oct)
00022       throw std::runtime_error("Octal output of BigInt not supported");
00023 
00024    if(n == 0)
00025       stream.write("0", 1);
00026    else
00027       {
00028       if(n < 0)
00029          stream.write("-", 1);
00030       const std::vector<byte> buffer = BigInt::encode(n, base);
00031       size_t skip = 0;
00032       while(skip < buffer.size() && buffer[skip] == '0')
00033          ++skip;
00034       stream.write(reinterpret_cast<const char*>(&buffer[0]) + skip,
00035                    buffer.size() - skip);
00036       }
00037    if(!stream.good())
00038       throw Stream_IO_Error("BigInt output operator has failed");
00039    return stream;
00040    }
00041 
00042 /*
00043 * Read the BigInt from a stream
00044 */
00045 std::istream& operator>>(std::istream& stream, BigInt& n)
00046    {
00047    std::string str;
00048    std::getline(stream, str);
00049    if(stream.bad() || (stream.fail() && !stream.eof()))
00050       throw Stream_IO_Error("BigInt input operator has failed");
00051    n = BigInt(str);
00052    return stream;
00053    }
00054 
00055 }