sigmund
sigmund

Reputation: 39

How to output a 4 byte string as a 4 byte integer in CPP

I am currently working on a Hash function and need to interpret a 4 byte string as a 4 byte integer number. Specifically I want every char value of the string interpreted as part of the integer number.

Upvotes: 0

Views: 758

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You can just copy the 4 bytes into a 32 bit unsigned integer variable to be able to interpret it as a 4 byte integer:

#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
}

Upvotes: 2

sigmund
sigmund

Reputation: 39

This function takes a string and interprets its char values as a 4 byte integer number. Only tested strings with a maximum length of 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;
            } 

Upvotes: 1

Related Questions