I need to convert a long variable to a char array. How to organize it?

  • one
    In what sense? 4 bytes to a 4-byte array? Or a value of type long in string representation? - Harry

2 answers 2

#include <string> const std::string str=std::to_string(my_value); str.c_str() - нужный массив 
  • Funny. Personally, I first took the question as char a[4]; memcpy(a,&l,4); char a[4]; memcpy(a,&l,4); ... - Harry

The question allows ambiguous interpretation. :-) My answer is:

 // Example program #include <iostream> #include <string> int main() { long vallong=0x0102030405060708; char* charptr=(char*)(&vallong); std::cout <<std::endl<< "sizeof(long)=" << sizeof(long); std::cout <<std::endl<< "charptr=" << (int)charptr[0]; std::cout <<std::endl<< "charptr=" << (int)charptr[1]; std::cout <<std::endl<< "charptr=" << (int)charptr[2]; std::cout <<std::endl<< "charptr=" << (int)charptr[3]; std::cout <<std::endl<< "charptr=" << (int)charptr[4]; std::cout <<std::endl<< "charptr=" << (int)charptr[5]; std::cout <<std::endl<< "charptr=" << (int)charptr[6]; std::cout <<std::endl<< "charptr=" << (int)charptr[7]; } 

The output of the program:

sizeof (long) = 8
charptr = 8
charptr = 7
charptr = 6
charptr = 5
charptr = 4
charptr = 3
charptr = 2
charptr = 1
Exit code: 0 (normal program termination)

Checked on cpp.sh