Sending Hexadecimal data through Serial Port Communication in Linux

后端 未结 3 620
旧巷少年郎
旧巷少年郎 2021-01-03 09:11

I have got a task of sending hexadecimal data to my COMPORT in linux. I have written this simple C code, but it sends only a decimal number. Can anyone help me in sending an

3条回答
  •  余生分开走
    2021-01-03 09:34

    This function will take a hex string, and convert it to binary, which is what you want to actually send. the hex representation is for humans to be able to understand what is being sent, but whatever device you are communicating with, will probably need the actual binary values.

    // Converts a hex representation to binary using strtol()
    unsigned char *unhex(char *src) {
      unsigned char *out = malloc(strlen(src)/2);
      char buf[3] = {0};
    
      unsigned char *dst = out;
      while (*src) {
        buf[0] = src[0];
        buf[1] = src[1];
        *dst = strtol(buf, 0, 16);
        dst++; src += 2;
      }
    
      return out;
    }
    

提交回复
热议问题