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 two signed 8-bit integers given in hexadecimal representation and returning the hexadecimal representation of the signed 8-bit sum:
hex1 = 'AA';
hex2 = '2F';
signeddec1 = typecast(uint8(hex2dec(hex1)), 'int8');
signeddec2 = typecast(uint8(hex2dec(hex2)), 'int8');
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 two signed 16-bit integers given in hexadecimal representation and returning the hexadecimal representation of the signed 16-bit sum:
hex1 = 'AA10';
hex2 = '2FDE';
signeddec1 = typecast(uint16(hex2dec(hex1)), 'int16');
signeddec2 = typecast(uint16(hex2dec(hex2)), 'int16');
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 two signed 32-bit integers given in hexadecimal representation and returning the hexadecimal representation of the signed 32-bit sum:
hex1 = 'AA10EFDE';
hex2 = '2FDE01CB';
signeddec1 = typecast(uint32(hex2dec(hex1)), 'int32');
signeddec2 = typecast(uint32(hex2dec(hex2)), 'int32');
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 use hex2dec 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 (with sscanf for example).