Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from const char* to unsigned int c++

Tags:

c++

I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck. I have a:

const char* charVar;

and i need to convert it to:

unsigned int uintVar;

How can it be done in C++?

Thanks

like image 805
Bizwoo Avatar asked Oct 26 '10 14:10

Bizwoo


People also ask

What is const unsigned char *?

const char* is useful for pointer to a string that will not change. ie your program will print some string, like the same welcome messages every time it starts. The unsigned version is useful for pointer to a binary sequence you may want to write too a file.

How to convert char to unsigned int in c++?

You can convert a char array to an integer using atoi: char *in = "4793"; int out = atoi(in);

What is const char * in CPP?

char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.

How do I convert an int to unsigned?

1) Add UINT_MAX + 1 to your signed number and store it in an unsigned variable. (this will convert the signed integer to an unsigned integer of same magnitude). 2) Unsigned number of same binary representation can be found by multiplying each digit in the binary representation by its place value and adding them up.


2 Answers

#include <iostream>
#include <sstream>

const char* value = "1234567";
stringstream strValue;
strValue << value;

unsigned int intValue;
strValue >> intValue;

cout << value << endl;
cout << intValue << endl;

Output:

1234567

1234567

like image 157
Steve Townsend Avatar answered Sep 28 '22 02:09

Steve Townsend


What do you mean by convert?

If you are talking about reading an integer from the text, then you have several options.

Boost lexical cast: http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

String stream:

const char* x = "10";
int y;
stringstream s(x);
s >> y;

Or good old C functions atoi() and strtol()

like image 23
Šimon Tóth Avatar answered Sep 28 '22 01:09

Šimon Tóth