I have a hex value stored in a two byte array:
unsigned char hex[2] = {0x02, 0x00};
How can I convert this to a decimal value?
To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.
The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.
There is no special type of data type to store Hexadecimal values in C programming, Hexadecimal number is an integer value and you can store it in the integral type of data types (char, short or int).
One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );
Use std::strtol Function to Convert Char Array to an Int. strtol method interprets the first valid characters from char array to an integer type. The function takes the number base for the converted integer as a third parameter, with a value from the {0,2,3,...,36} range.
Some reasons as to why this is not correct: First you are shifting the first char by 16 bits instead of 8 bits. A char is typically 8 bits. Second you are ANDing the two parts, you need to OR them. By shifting hex [0] over you are leaving the first 16 bits as zeros and when ANDed with hex [1] you will effectively remove hex [1].
The "hex values" for the initialisation are irrelavant - each element is char but unsigned char would be better. Why do you say that {0, 9, 39, 192} is "600,000" in decimal? you are sign-extending the values when casting to int. 0xC0 is 10100000 in binary.
Print the integer using cout. Below is the C++ program to convert char to int using typecasting: Declare and initialize our character to be converted. Declare another variable as int N and assign the character ch to the N. Print the integer using cout. Below is the C++ program to convert char to int using typecasting: 2. Using static_cast
You can use (bitwise operation)
int b = (hex[0] << 8) | hex[1];
or (simple math)
int b = (hex[0] * 0x100) + hex[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With