Search code examples
c++stringhexstrtol

How to convert from a binary string of 32 characters to hex?


I know there are tons of tutorials online about how to convert from a string to hex. Well, I am having an issue with that.

My code (see below) works up to 31 characters and I cant for the life of me figure out why. Whenever there are 32 character it just maxes out at 7fffffff.

I need to be able to input something like "111111111100000000001010101000"

Should be an easy fix just not sure where

My attempt (compilable):

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    int Base = 2;
    long x;
    char InputString[40];
    char *pEnd = NULL;          // Required for strtol()


    cout << "Number? ";
    cin >> InputString;
    x = strtol(InputString, &pEnd, Base);     // String to long

    cout << hex << x << endl;
    return 4;
}

Solution

  • This probably happens because the long is 32 bits on your machine and a signed long can't hold 32 bits in 2's complement. You could try to use an unisgned (which doesn't "waste" a bit for the sign) or a long long which is 64 bits wide.

    unsigned long x = strtoul(InputString, &pEnd, Base);
                        ^^^^
    

    Or long long:

    long long x = strtoll(InputString, &pEnd, Base);
    

    The functions strtol and strtoul have been available for a long time in C++. Indeed strtoll and long long have been introduced in C++11.