How to convert hex two's complement to integer (e.g hex 810 to int -2032)

3 views (last 30 days)
I would like to convert hex values which are defined in twos complement into int.For instance hex 810 convert in -2032. My first approach was to do it step by step. Convert to binary, Check msb for sign and then convert data accordingly. However I guess there might be a function available which can handle this issue easily??

Accepted Answer

Walter Roberson
Walter Roberson on 17 Aug 2021

Current versions can have hex constants

 0xF810s16

If you happen to have the hex as a variable

s = 'f810' 
typecast(uint16(sscanf(s, '%x')), 'int16') 

Using sscanf is not the fastest possible way for larger arrays, but typecast is faster than if statement checking the range. I posted a number of timing tests about 2 weeks ago in discussions with Robert.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!