簡體   English   中英

如何在 CPP 中將 4 字節字符串輸出為 4 字節整數

[英]How to output a 4 byte string as a 4 byte integer in CPP

我目前正在研究 Hash 函數,需要將 4 字節字符串解釋為 4 字節整數。 具體來說,我希望將字符串的每個字符值解釋為整數的一部分。

您可以將 4 個字節復制到 32 位無符號整數變量中,以便能夠將其解釋為 4 個字節整數:

#include <cstdint>
#include <cstring>
#include <iostream>
#include <string>

std::uint32_t foo(const std::string& str) {
    if(str.size() != 4) throw std::runtime_error("wrong string length");

    std::uint32_t rv;
    std::memcpy(&rv, str.c_str(), 4);
    return rv;
}

int main() {
    std::cout << (1 + 256 + 65536 + 16777216) << '\n'; // 16843009
    std::cout << foo("\001\001\001\001") << '\n';      // 16843009

    // The result is platform dependent, so these are possible results:

    std::cout << foo("\004\003\002\001") << '\n';  // 16909060 or 67305985
    std::cout << foo("\001\002\003\004") << '\n';  // 16909060 or 67305985
}

該函數接受一個字符串並將其字符值解釋為一個 4 字節的整數。 僅測試最大長度為 4 的字符串。

  uint32_t buffToInteger( std::string buffer ) 
            {
                uint32_t b = 0;
                for ( uint64_t i = 0; i < buffer.length(); i++ )
                {
                    b |= static_cast< unsigned char >(buffer.at( i ) << (24 - (4 - buffer.length() + i) * 8));
                }
                return b;
            } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM