[英]C++ How to convert a big integer in std::string form to byte/char-array/vector
我目前正在使用一個到目前為止看起來非常有用的BigInt 庫。
但我想將計算結果存儲到二進制文件中以備后用。
由於原因(二進制模式、文件大小等),僅存儲字符串不是一種選擇。
必須存儲實際值以供以后讀取。
我正在尋找的示例代碼:
BigInt example = BigInt("4");
std::vector<uint8_t> bytes = to_bytes(example);
想要的結果示例:
"4" ---> [0000 0100] //BigInt("4");
"255" --> [1111 1111] //BigInt("256");
"542" --> [0000 0010] [0001 1110] //...
"123456" --> [0000 0001] [1110 0010] [0100 0000]
“高得離譜的數字” --> [?] [?] [?] [?]... [n-bytes]
當然反過來:
std::vector<uint8_t> bytes = readbytes(file, n-bytes);//already have this
BigInt result = from_bytes(bytes);
所以基本上,我需要to_bytes()
和from_bytes()
函數。
我正在使用 C++20。
價值觀都是積極的,但兩種解決方案都是受歡迎的。
最好找到一個內置此功能的大整數庫。 這個庫甚至沒有 shift 運算符支持。 因此,您將不得不做一堆可能非常慢的事情(特別是考慮到該庫對字符串進行大整數數學運算)並且比它給您一個體面的界面要慢得多。
要將這么大的 integer 轉換為一系列字節,您必須單獨重復提取每個字節的數據。 這里的“字節”是每 2 8個數字。 如果沒有位移運算符,它將涉及很多除法和模運算。
std::uint8_t extract_one_byte(BigInt &extract)
{
auto intermediate = (extract % 256).to_int(); //Will always return a value on the range [0, 255]
std::uint8_t the_byte = static_cast<std::uint8_t>(intermediate);
extract /= 256;
return the_byte;
}
std::vector<std::uint8_t> to_bytes(const BigInt &source)
{
std::vector<std::uint8_t> ret;
//ret.reserve(#); //pick a decent amount to reserve.
BigInt curr = source;
do
{
ret.push_back(extract_byte(curr));
} while(curr != 0);
return ret;
}
請注意,這會以 little-endian 順序提取字節(最低有效優先)。 如果你需要大端,那么你必須在構造后std::reverse
vector
。 向后構建向量涉及更多的數據復制。
回去基本上是做相反的事情(從小端):
BigInt from_bytes(const std::vector<std::uint8_t> &le_bytes)
{
BigInt ret = 0;
for(auto curr_byte : le_bytes)
{
ret *= 256;
ret += curr_byte;
}
return ret;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.