Convert a four-character string to a long one

I want to convert a string of four characters (i.e. four characters) to a long one (i.e. convert them to ASCII codes, and then paste them into a long one).

As I understand it, this is done by writing the first character to the first byte of a long one, the second to an adjacent memory location, etc. But I do not know how to do this in C ++.

Can anyone point me in the right direction?

Thanks in advance.

+3
source share
3 answers

Here is your four character set:

const unsigned char buf[4] = { 'a', '0', '%', 'Q' };

Now we are collecting a 32-bit unsigned integer:

const uint32_t n = (buf[0]) | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

Here I assume that buf[0]is the least significant; if you want to go the other way around, just swap the indices around.

Confirm:

printf("n = 0x%08X\n", n); // we get n = 0x51253061
                           //               Q % 0 a

: , , , (unsigned int)(unsigned char)(buf[i]); .


: const uint32_t n = *(uint32_t*)(buf), , , !


, , :

const unsigned very long int n = buf[0] |
              (buf[1] << (CHAR_BIT)     |
              (buf[2] << (CHAR_BIT * 2) |
              (buf[3] << (CHAR_BIT * 3)   ;

! ( printf;-).)

+8

, memcpy, - -

#include <cstdlib>
#include <iostream>

int main()
{
    char data[] = {'a', 'b', 'c', 'd'};
    long result;

    std::memcpy(&result, data, 4);
    std::cout << result << "\n";
}

, , , . 4 . , 4 . , memcpy, , .

: , - , , !

+1
#include <string>
#include <iostream>

std::string fourCharCode_toString ( int value )
{
    return std::string( reinterpret_cast<const char*>( &( value ) ), sizeof(int) );
}

int fourCharCode_toInt ( const std::string & value )
{
    return *( reinterpret_cast<const int*>( value.data() ) );
}

int main()
{
    int a = 'DROW';
    std::string str = fourCharCode_toString( a );
    int b = fourCharCode_toInt( str );

    std::cout << str << "\n";
}
0
source

All Articles