# Issue

I'm receiving the following data over a serial port: `<0x1b><0x2e><0x15>...`

Each value enclosed in `'<>'`

is a single byte.

I require the third byte from the data so i do this:

```
int Length;
char Data[..];
Length = Data[2];
```

But the value of Length is 21 and not 15 because the value written in memory is hex. How do i convert the decimal representation of 15 to decimal 15?

I've tried converting it to various types and so on.. But none of that works for me as i'm writing a driver and performance matters a lot. I've looked over stackoverflow and other sites but all the given examples are with strings, none are with plain integers.

When i send it to the rest of the algorithm i run into issues as the algorithm expects 15.

# Solution

Given `int x`

that contains 8 bits that represent a number using natural packed binary-coded decimal, they can be converted to the number with:

```
int y = x/16*10 + x%16;
```

`x/16`

produces the high four bits, and then multiplying by ten scales them to the tens position. `x%16`

produces the low four bits. They are kept in the ones position and added to the tens.

Answered By - Eric Postpischil Answer Checked By - David Marino (PHPFixing Volunteer)

## 0 Comments:

## Post a Comment

Note: Only a member of this blog may post a comment.