How to Add signed 8-bit from unsigned 16-bit?

352 views Asked by At

I'm having trouble understanding how to do the following:

I have an array of uint8_t elements. From this array, I want to acquire an element and add it to a uint16_t item. However I want to interpret this uint8_t value as a signed value for the purposes of this operation.

uint16_t A;
uint8_t  B;
uint16_t result;

result = A + (int8_t)B;

However I learned that this casting might not work. I can't think of any other way to get this to work. It's important that the elements of my array remain as uint8_t otherwise. Only for this operation, do I want the uint8_t element interpreted as a signed value (int8_t).

1

There are 1 answers

3
chqrlie On BEST ANSWER

You have been misinformed: There is nothing wrong with your code, and nothing that supports the claim that this casting might not work.

Technically, there is a very slim possibility that the type int8_t be unavailable on your system, but in this very unlikely case, uint8_t would not be defined either. Such systems include some DSPs and some obsolete mainframes. If you are programming to a more mainstream system, don't worry about it.