0

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;
}
cmonnats23
  • 15
  • 1
  • 6

2 Answers2

1

A long can't store more than 32 bits (actually 31 plus a sign bit). Try a long long int and strtoll() if you want more than 32 bits, or unsigned long and strtoul() if 32 is enough.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
  • `long long` where? on the initialization of the x? That didnt work. Theough, you bring up a good point. maybe I cant use the strtol function because its converting it to a long which is only 32 bits? – cmonnats23 Oct 03 '13 at 08:59
1

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • your solution makes sense, however, there is no known library for either stroll nor strtoul – cmonnats23 Oct 03 '13 at 09:01
  • @cmonnats23 I edited my answer. Use `strtoul` if you don't have `long long`. – cnicutar Oct 03 '13 at 09:03
  • what are the cons with making x unsigned and using strtoul? like, why would that be bad? also, not sure when C++11 was released, but on VS2012, strtoll is not available. unless theres something different I have to #include – cmonnats23 Oct 03 '13 at 09:07
  • @cmonnats23 The cons ? Dealing with `unsigned` quantities can be tricky, that's about it. – cnicutar Oct 03 '13 at 09:08
  • meh, its just reading the number in and converting it. should be fine i would think. thanks. id upvote you, but dont have enough rep yet. – cmonnats23 Oct 03 '13 at 09:09
  • @cmonnats23 Wait, don't accept yet! Better answerers might turn up and an accepted answer will deter them. – cnicutar Oct 03 '13 at 09:10