-1

I'm fiddling around with a set of i2c addresses from a file. The i2c addresses are all unsigned chars and looks like '0x20' or '0x27'.

The problem is when reading from the file i get an array of char, and i cant figure out how to convert the char[] "0x21" to the unsigned char '0x21'.

is there something similar to printf("0x%02x", address[i]); but works in the other direction?

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Q: What do you mean by "convert"? A "char" and an "unsigned char" have *EXACTLY THE SAME BITS* - there's no "conversion" required. Perhaps you mean [cast](https://www.tutorialspoint.com/cprogramming/c_type_casting.htm)? EXAMPLE: `printf("0x%02x", (unsigned char)address[i]);` – paulsm4 Aug 14 '21 at 06:11
  • Sorry, my misstake. Yes i mean cast not convert. If i init i2c with unsigned char 0x21, everything works, but if i try to initialize with normal char[] it segfaults. – Andreas Björksved Aug 14 '21 at 06:59
  • 1
    It is unclear what is being asked. Is it a text file or a binary file? What is the *exact* file content? How are you reading it? Why don't you read it into an array of `unsigned char` if that is what you want? – Weather Vane Aug 14 '21 at 07:17
  • 1
    *`if i try to initialize with normal char[] it segfaults.`* - `char[]` is not `char` , – 0___________ Aug 14 '21 at 07:53
  • How to? Start from https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – 0___________ Aug 14 '21 at 08:34
  • @WeatherVane the file is a normal textfile containing standard ascii chars. i use fopen(filname, "r"); – Andreas Björksved Aug 14 '21 at 13:37

1 Answers1

1

The question is basically: "How do I interpret a string as an unsigned char value?"

The C standard library header has several functions for these types of conversions, all named "strto*". The closest match for what you want to do is strtoul (string to unsigned long). The unsigned long can be cast to an unsigned char. Code example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[] = "0x21";

    unsigned char uc = (unsigned char) strtoul(str, NULL, 16);
    printf("%u\n", uc);
}

Which prints "33".

Yun
  • 3,056
  • 6
  • 9
  • 28
  • yes, that is my exact problem, i need it to be 0x21 not 31 :/ – Andreas Björksved Aug 14 '21 at 13:38
  • 2
    Do you mean 33? "0x21" and "33" are two different _representations_ of the same value. One is base 16 and the other one is base 10. In other words, `unsigned char a = 0x21;` has exactly the same effect as `unsigned char a = 33;`. – Yun Aug 14 '21 at 13:48
  • ...which can be seen from `printf("%u 0x%x\n", uc, uc);` which outputs `33 0x21` – Weather Vane Aug 14 '21 at 16:50