Doe
Doe

Reputation: 45

How to properly receive hex data from serial communication in linux

I have been searching for this similar issue on internet but haven't found any good solution. I am in ubuntu and I am receiving serial hex data on serial port. I have connected my system using null modem cable to windows system and windows system is running docklight software which is sending hex data like below:

2E FF AA 4F CC 0D

Now by saving the data, I do not mean that I want to print data on terminal. I just want to save this data as it is in a buffer so that I an later process it.

To read the data I am doing

res = read (fd, buf, sizeof buf)
//where buf is 
unsigned char buf[255];

At this point after reading, buf contains some random chars. From some links on internet, I got a way to convert it into hex:

unsinged char hexData[255];
for (int i = 0; i < res; i++)
{
    sprintf((char*)hexData+i*2, "%02X", buf[i]);
}

Now this hexData contains 2EFFAA4FCC0D, which is ok for my purpose. (I do not know if it is the right way of doing it or not). Now lets say I want to convert E from the hexData into decimal. But at this point, E will be considered as character not a hex so may be I'll get 69 instead of 14.

How can I save hex data in a variable. Should I save it as array of chars or int. Thanks.

Upvotes: 2

Views: 2265

Answers (2)

Pras
Pras

Reputation: 4044

You already have data in binary form in buf

But if you still need to convert hex to decimal, you can use sscanf

sscanf(&hexBuf[i],"%02X",&intVar);// intVar is integer variable

It wll convert hex byte formed by hexBuf[i] and hexBuf[i+1] to binary in intVar, When you printf intVar with %d you will get to see the decimal value

You can store intVar as element of unsigned character array

Upvotes: 1

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

You may want to think about what you're trying to achieve.

Hexadecimal is just a representation. The byte you are receiving could be shown as hexadecimal pairs, as binary octet or as a series of (more or less) printable characters (what you see if you print your unsigned char array).

If what you need is storing only the hexadecimal representation of those bytes, convert them to hexadecimal as you are doing, but remember you'll need an array twice as big as your buffer (since a single byte will be represented by two hexadecimal characters once you convert it).

Usually, the best thing to do is to keep them as an array of bytes (chars), that is, your buf array, and only convert them when you need to show the hexadecimal representation.

Upvotes: 1

Related Questions