Borrar filtros
Borrar filtros

How can I write the Twos complement and return a hex string ?

32 visualizaciones (últimos 30 días)
Irwin2020
Irwin2020 el 22 de Oct. de 2018
Comentada: Irwin2020 el 24 de Nov. de 2018
Ex:
E5
+
83
=
8E
I k
% ~add 1 to bin_int
*****************************************
Thank you.
  8 comentarios
Guillaume
Guillaume el 25 de Oct. de 2018
And as I said, -142 is not representable as 8-bit integer. So what should the answer be? Matlab answer would be -128, for a C program this would be undefined and could result in anything although some implementations may return +114.
madhan ravi
madhan ravi el 20 de Nov. de 2018
If you close the question that have answers you will unlikely receive any help further plus it ignores the efforts of the answerers

Iniciar sesión para comentar.

Respuesta aceptada

Guillaume
Guillaume el 25 de Oct. de 2018
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).
  1 comentario
James Tursa
James Tursa el 29 de Oct. de 2018
"... regardless to their lengths ..."
You are required to use for-loops for this assignment?

Iniciar sesión para comentar.

Más respuestas (2)

James Tursa
James Tursa el 29 de Oct. de 2018
Editada: James Tursa el 29 de Oct. de 2018
If you really have to write a for-loop for this, a simple algorithm for adding two 2's complement signed integers represented as hex strings is:
1) Convert each hex string to binary strings of the appropriate length (based on location of sign bit)
2) Add up the bits in the usual fashion ignoring overflow (e.g., grade school arithmetic using a carry bit. SEE NOTE!)
3) Look for overflow (both operands are the same sign but result is opposite sign)
4) Convert the result binary string back into hex
NOTE: You don't have to do anything special for step 2 regarding the signs of the operands. You just add up the bits (including the "sign" bit) like normal grade school arithmetic. If the carry bit overflows past the sign bit in this process you simply ignore it. Doing it this way, the bits of the answer will be correct regardless of the signs of the operands ... just make sure you treat the sign bit just like any other bit in this adding process. Then all you need is the simple check for overflow by examining the signs of the operands and the sign of the result. Of course, you may simply choose to ignore any actual overflow and let the result wrap around like many C/C++ compilers do.
  12 comentarios
James Tursa
James Tursa el 2 de Nov. de 2018
Putting that in a loop will be the easy part. It is the sign bit and overflow stuff that will be the hard part. Do you have any constraints on where the sign bit might be? Will it always be at the left edge of a 2-byte boundary? Or could it be anywhere? Writing generic code for a sign bit that could be anywhere could easily take up the bulk of your code and will be more complicated than what I have already written above, whereas if you restrict the cases to 2-byte boundaries that simplifies things greatly.
Guillaume
Guillaume el 2 de Nov. de 2018
all I need is that if you are able to show me a for loop (i) to add the hex values
I have done just that in the answer that at the moment is below this one.
With regards to sign bits. We still haven't had any explanation of how that work with variable length hex strings. Having a sign bit that moves around would be completely nonsensical. Would FF be the signed 8-bit decimal value -1 or the signed 16-bit decimal value 255? The only thing that would work would be if the sign bit was the LSB.

Iniciar sesión para comentar.


Guillaume
Guillaume el 1 de Nov. de 2018
Function to add hexadecimal strings of arbitrary length:
function hexsum = addhex(hex1, hex2)
assert(all(ismember(hex1, '0123456789ABCDEF')), 'hex1 is not a hexadecimal string');
assert(all(ismember(hex2, '0123456789ABCDEF')), 'hex2 is not a hexadecimal string');
%pad both strings to the same length and to a length multiple of 2 for easy byte conversion
maxlength = 2*ceil(max(numel(hex1), numel(hex2))/2);
hex1 = [repelem('0', maxlength - numel(hex1)), hex1];
hex2 = [repelem('0', maxlength - numel(hex2)), hex2];
%split into bytes, convert to decimal
dec1 = hex2dec(reshape(hex1, 2, [])');
dec2 = hex2dec(reshape(hex2, 2, [])');
%sum with carry
decsum = zeros(size(dec1));
carry = 0;
for row = numel(dec1):-1:1
decsum(row) = dec1(row) + dec2(row) + carry;
carry = decsum(row) > 255;
end
decsum = mod(decsum, 256);
%convert back to hex, remove leading 0
hexsum = reshape(dec2hex(decsum, 2)', 1, []);
hexsum = hexsum(~cumprod(hexsum == '0'));
end
The numbers are assumed unsigned as otherwise you would have to specify the sign bit. A loop is only needed for the addition with carry. For everything, it's simpler to do it without a loop.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by