MATLAB: How to write the Twos complement and return a hex string
homeworksum 2 hex strings
Ex:
E5
+
83
=
8E
I k
% ~add 1 to bin_int
*****************************************
Thank you.
Best Answer
There's a reason I ask all these questions. I don't believe you've thought properly about what it is you're asking. As I keep saying repeatedly saying a number is signed is meaningless if you don't specify how many bits. '8E' represents a negative number on 8-bit. It represents a positive number on 9-bits or more. And it's not a valid number on less than 8-bit.
Anyway, 2-complement addition of hexadecimal numbers:
Adding twosigned 8-bit integers given in hexadecimal representation and returning the hexadecimal representation of thesigned 8-bit sum:
result = dec2hex(typecast(signeddec1 + signeddec2, 'uint8'))
Of course, since we're working with 8 bits, hexadecimal with more than 2 digits makes no sense and will be interpreted as 'FF'. Also, since we're working with signed 8 bit, any sum below -128 or +127 makes no sense and will result in -128 or +127.
Adding twosigned 16-bit integers given in hexadecimal representation and returning the hexadecimal representation of thesigned 16-bit sum:
result = dec2hex(typecast(signeddec1 + signeddec2, 'uint16'))
Of course, since we're now working with 16 bits, hexadecimal with more than 4 digits makes no sense and will be interpreted as 'FFFF'. Also, since we're working with signed 16-bit,'8E' is not a negative value. Negative values start at '7FFF'. And since we're working with signed 8 bit, any sum below -32768 or +32767 makes no sense and will result in -32768 or +32767.
Adding twosigned 32-bit integers given in hexadecimal representation and returning the hexadecimal representation of thesigned 32-bit sum:
result = dec2hex(typecast(signeddec1 + signeddec2, 'uint32'))
Same comments apply, except now the maximum is 8 hexadecimal digits and the bounds are -2147483648 to +2147483647.
For signed 64-bit integers, equivalent to 16 hexadecimal digits, you can no longer usehex2dec as numbers may fall outside the range that it can safely convert (anything greater than hex '20000000000000'). There are slightly more complicated ways to reliably parse the hexadecimal however (withsscanf for example).
I suspect the problem is actually in hex2dec(). You are exceeding the flintmax limit described in the hex2dec documentation:
d = hex2dec('hex_value') converts hex_value to its floating-point integer representation. The argument hex_value is a hexadecimal integer stored as text.If the value of hex_value is greater than the hexadecimal equivalent of the value returned by flintmax, then hex2dec might not return an exact conversion.
Best Answer