How can I type cast char* to a long value?

e.g. char * abc ;
long xyz;
xyz = abc????

xyz = *(long *)abc; That works when you KNOW that the character buffer contains the binary value of the long integer. For example

int main()
{
    char abc[10] = {0};
    long xyz = 123;
    memcpy(abc,&xyz,sizeof(long));
    long xxx = *(long *)abc;
    cout << xxx << "\n";
}

Ed should emphasize that Ancient Dragon was talking about the binary value of a long int, not the character representation. A lot of times when people want to "cast" a string to another type they really mean a string conversion rather than a real cast:

#include <exception>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <typeinfo>

long ParseLong(const std::string& src)
{
  std::istringstream iss(src);
  long result;

  if (!(iss >> result)) {
    throw std::bad_cast(("Incompatible representation "
      "from \"" + src + "\" to long").c_str());
  }

  return result;
}

int main()
{
  try {
    std::string input;

    std::cout << "Enter a long int: ";
    std::getline(std::cin, input);
    
    long converted = ParseLong(input);

    std::cout << "Squared: " << converted * converted << '\n';
  } catch (const std::exception& ex) {
    std::cerr << "Error detected: " << ex.what() << '\n';
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.