Convert char* to uint8_t [2 methods]

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have covered different approaches to convert char* to uint8_t.

Table of contents:

  1. Approach 1: Using atoi
  2. Approach 2: Copy bits

Approach 1: Using atoi

In this approach, we convert char* to integer (32 bit) using the standard function atoi() and convert the 32 bit integer to 8 bit unsigned integer (uint8_t).

atoi() is defined in stdlib.h header file.

char* input = "110";
uint8_t input2 = (uint8_t)atoi(input);

Following is the complete C++ code to convert char* to uint8_t using atoi():

#include <stdlib.h>

int main() {
  char* input = "110";
  uint8_t input2 = (uint8_t)atoi(input);
  return 0;
}

Approach 2: Copy bits

Char datatype is of size 8 bits and uint8_t is of 8 bits as well. char* is a memory address of 32 bits or 64 bits pointing to a data (string) of variable size.

If you wish to copy the first 8 bits binary representation of a char using char*, then the approach is to assign the uint8_t variable the value pointed to by char*.

char input1;
char * input2 = &input1;
uint8_t input3 = *input2;

Following is the complete C++ code following this approach:

#include <stdlib.h>

int main() {
  char input1 = 'A'; // Value 65
  char * input2 = &input1;
  uint8_t input3 = *input2;
  return 0;
}

With this article at OpenGenus, you must have the complete idea of how to convert a char* to uint8_t.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.