15

I have a variable unsigned char that contains a value, 40 for example. I want a int variable to get that value. What's the simplest and most efficient way to do that? Thank you very much.

user1346664
  • 189
  • 1
  • 1
  • 8
  • 2
    unsigned char is essentially a one byte of memory interpreted by the computer as an integer it is from 0 to 255. An integer type is usually 4 bytes with range -2147483648 to 2147483647. Conversion usually involves assignments from one value to another. unsigned char to integer assignment is no problem, but the other way around will have over flow problems at the high end. And it not meaning full to convert negative number to unsigned char. – Kemin Zhou Dec 09 '18 at 04:34

6 Answers6

20
unsigned char c = 40;
int i = c;

Presumably there must be more to your question than that...

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
7

Try one of the followings, it works for me. If you need more specific cast, you can check Boost's lexical_cast and reinterpret_cast.

unsigned char c = 40;
int i = static_cast<int>(c);
std::cout << i << std::endl;

or:

unsigned char c = 40;
int i = (int)(c);
std::cout << i << std::endl;
2

Google is a useful tool usually, but the answer is incredibly simple:

unsigned char a = 'A'
int b = a
NominSim
  • 8,447
  • 3
  • 28
  • 38
2

Actually, this is an implicit cast. That means that your value is automatically casted as it doesn't overflow or underflow.

This is an example:

unsigned char a = 'A';
doSomething(a); // Implicit cast

double b = 3.14;
doSomething((int)b); // Explicit cast neccesary!

void doSomething(int x)
{
...
}
bytecode77
  • 14,163
  • 30
  • 110
  • 141
2

Depends on what you want to do:

to read the value as an ascii code, you can write

char a = 'a';
int ia = (int)a; 
/* note that the int cast is not necessary -- int ia = a would suffice */

to convert the character '0' -> 0, '1' -> 1, etc, you can write

char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
Nurzhan Aitbayev
  • 797
  • 1
  • 10
  • 23
-1
char *a="40";
int i= a;

The value in 'a' will be the ASCII value of 40 (won't be 40).

Instead try using strtol() function defined in stdlib.h

Just be careful because this function is for string. It won't work for character

user1030768
  • 265
  • 2
  • 5
  • 13
  • 2
    The value of `a` (and of `i`) *will* be 40, as that is the value you just assigned. – Bo Persson May 12 '12 at 12:42
  • 2
    If you ignore the compiler warning you'll discover that `i` gets the address where the string "40" is stored, which is of course what 'a' has in it. Ah - brings back to good ol' days before that wimpy ANSI standard thing - back when C was weakly typed, programmers had stronger minds, and Coca-Cola was made with real sugar! Bah! Kids these days..! Bah!! – Bob Jarvis - Слава Україні May 13 '13 at 16:53
  • 1
    The question was about unsigned char. Why are you using a char*? – Aamir May 13 '13 at 16:54