Convert BYTE array to unsigned long long int

I am trying to convert a BYTE array to the equivalent value of unsigned long long int, but my encoding is not working properly. Help with fixing it or suggest an alternative method for this.

Additional information: these 4 bytes are combined as a hexadecimal number, and the equivalent decimal number is the result. Say for a given byte, Array = {0x00, 0xa8, 0x4f, 0x00}, the hexadecimal number is 00a84f00, and its equivalent decimal number is 11030272.

#include <iostream>
#include <string>

typedef unsigned char BYTE;

int main(int argc, char *argv[])
{
  BYTE byteArray[4] = { 0x00, 0x08, 0x00, 0x00 };
  std::string str(reinterpret_cast<char*>(&byteArray[0]), 4);
  std::cout << str << std::endl;

  unsigned long long ull = std::strtoull(str.c_str(), NULL, 0);
  printf ("The decimal equivalents are: %llu", ull);


  return EXIT_SUCCESS;
}

I get the following output:

The decimal equivalents are: 0

So far, the expected result has been:

The decimal equivalents are: 2048
+4
source share
3 answers

std::strtoull(str.c_str(), NULL, 0);, , - , , .

-, std::strtoull() , . .. 2048 std::strtoull("2048", NULL, 10).

: unsigned long long - 64- , - 32 . 32 , . , std::memset() .

:

ull = 0ULL;
std::memcpy(&ull, byteArray, 4);

, little-endian, 2048.

+4

, - . -, , , . , , 32- , ( ) 64- , 8 .

, std::memcpy :

uint32_t temp;
std::memcpy(&temp, byteArray, 4);
ull = temp;

, , endianness .


, std::memcpy std::copy ( std::copy_n), , std::memcpy , , std::copy, , std::copy , ( , clunkier ).

+3

, std::memcpy, , :

char byteArray[] = { 0x00, 0x08, 0x00, 0x00 };
uint32_t cp;
std::copy(byteArray, byteArray + sizeof(cp), reinterpret_cast<char*>(&cp));

std::copy std::memcpy, ++ .

, cp : char *, unsigned char *, signed char * std::byte *, .

+2

Source: https://habr.com/ru/post/1693077/


All Articles