You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
Please help me create Decimal to Two's Complement/ Two's Complement to Decimal function without using the built-in function in Matlab
7 views (last 30 days)
Show older comments
Hello Everyone,
My goal here is to create the Decimal to Two's Complement/ Two's Complement to Decimal function without using the built-in function in Matlab , aslo to create hexadecimal number to decimal number and vise versa. without using hex2dec & dec2hex.
Your input is much appreciated.
Thank you.
41 Comments
James Tursa
on 10 Dec 2018
What have you done so far? What specific problems are you having with your code? Are you working only with integers within a certain range?
Irwin2020
on 11 Dec 2018
Edited: Irwin2020
on 12 Dec 2018
32 or 64-bit , unsigned integer or an array of unsigned integers
function [bitwiseComplement] = twosComplement(x,bits)
% x = input variable (binary numbers) [11010100111.....bin-1]
if x >1
bin = nan
eles
bin =1
nBinery = numel(x)
bitwiseComplement=bits(bitxor(x, 2^bits-1) + 1) % Here is to do the 2s complements of biners
% Ex
%%
% 00011100
% 11100011
------------
% 11100100
%%
end
end
My goal is to Add Hex stringd and do 2s Compliment functions without using the Matlab functions.
Thank you.
James Tursa
on 11 Dec 2018
Edited: James Tursa
on 11 Dec 2018
What is "bineries"? Also, your bit calculations will immediately have problems because doubles do not have 64 bits of precision. I.e., the 2^bits-1 isn't going to give you what you expected if bits = 64.
Irwin2020
on 11 Dec 2018
Edited: Irwin2020
on 11 Dec 2018
I wanted x to be my input as a (binary number) EX; 00011100 and then
flip them to 11100100 and Add 1 to have this result 11100100 then I would convert this binary number to Hex char/s.
My ultimate goal here , is to create a function that adds hex numbers. as far as the bit calculations I would keep it as 32-bits if possible.
Walter Roberson
on 11 Dec 2018
Edited: Walter Roberson
on 11 Dec 2018
Your current code has
x = [binarynumber] % restrict the inputs betwen 0 and 1 [11010100111.....bin-1]
What is it that you expect that line to do ? It appears to overwrite the input variable, x but we do not know what binarynumber is ? Is it a function ?
Walter Roberson
on 12 Dec 2018
When the line
x = [binarynumber] % restrict the inputs betwen 0 and 1 [11010100111.....bin-1]
is executed, what are you expecting to have happen? What are you overwriting the variable x with ?
If the input to the function had been 9, then what would be the result after executing
x = [binarynumber] % restrict the inputs betwen 0 and 1 [11010100111.....bin-1]
?
If the input to the function had been 9.5, then what would be the result after executing
x = [binarynumber] % restrict the inputs betwen 0 and 1 [11010100111.....bin-1]
?
If the input to the function had been 10, then what would be the result after executing
x = [binarynumber] % restrict the inputs betwen 0 and 1 [11010100111.....bin-1]
?
Irwin2020
on 12 Dec 2018
I will write a function to add Hex strings later on, and for now, I 'm trying to create this 2s complement function , to complement any binary number s not decimal numbers , I will use this function with my add hex strings function later on.
This function will recognize the binary numbers and complement them, and only deals only with 0s and 1s
I'm trying to do this manually without using the built-in Matlab functions
Walter Roberson
on 12 Dec 2018
We recommend that you do not go back and edit your code without mentioning it. The people volunteering typically assume that the old code is still what you are using unless you specifically post new code or specifically say that you changed it and that we should go back to look.
Walter Roberson
on 12 Dec 2018
For the purpose of your function twosComplement, are the following legal calls ?
twosComplement(11, 8)
twosComplement(12, 8)
twosComplement('101', 8)
twosComplement(uint16(279), 8)
twosComplement(int16(-279), 8)
twosComplement('037f', 16)
Irwin2020
on 13 Dec 2018
The old code didn't work all the way, also the old code I have it just adds two Hex strings manually,, when I tested it on the command window worked fine, and when called it into another function (into for-loop) didn't work correctly, because of the signed Hex strings (Negative Hex values) messed-up my calculations, so I wanted to create a separate function to do the 2s complement to turn the negative Hex string positive Hex string before being added to another Hex string, is this explained my purpose here? ( Are we talking about addHexNumber function i.e the old code?).
Walter Roberson
on 13 Dec 2018
Are we talking about addHexNumber function i.e the old code?
No, we are talking about twosComplement . You failed to documented the permitted inputs, so I asked specific questions, listing potential input values and asking whether each of them is intended to be handled or not.
Is there any inverting method to invert a Hexa char value to a number( Integer) hex2int and vice versa without using Matlab functions??
No. It is not possible to do computation in MATLAB without using MATLAB functions. See https://www.mathworks.com/matlabcentral/answers/38787-what-can-be-programmed-without-any-built-in-functions . If you were to list a set of permitted functions, or alternately you were to list a set of excluded functions, then we could answer in terms of that set.
I would point out that ones-complement can be implemented for hex purely in terms of array lookups. Add-one can also be implemented in hex in terms of array lookups, but with a small bit of logic added. Twos-complement is ones-complement followed by Add-one. Therefore by induction, twos-complement can be implemented in hex in terms of array lookups with a small bit of logic added. You do not need to convert to decimal.
onesc('0123456789abcdef') = 'fedcba9876543210';
OnesComplement = @(TheInputHexCharacterVector) onesc(lower(TheInputHexCharacterVector))
Irwin2020
on 13 Dec 2018
Edited: Irwin2020
on 20 Dec 2018
Walter I really appreciate you for answering all my questions and I do value your inputs and the other guys who helps ppl like me, I'm trying really hard to learn Matlab in general,and you guys are really helpfull.
I have created my own Clockregister function as you can see below, this function have a counter would go and add Hex stings and return new result
function [result] = Clockregister01(R,count)
clc
for j = 1:count
for i = 1:size(RN,1)-1
% RN(i,1:size(RN,2)) = addHexNumber(RN(i,1:size(RN,2)),RN(i+1,1:size(RN,2)))
A = addHexNumber(RN(i,:),RN(i+1,:));
end
end
result = RN;
end
Whne I run the function for 1 count I get this
Clockregister01(R,1)
I get this answer
"000000007FE906A41162B1720C281817AA5644BC80"
"101010101010101017FE9016A4018D30117F0130133D8E7B8B2AF585"
"101010101010101010101010101010101F9A013F523AF2F4427196A476F8"
"1111111111111111113401F016B67E6548760193D6A9AB"
"10101010101010101010101010101010101010101010101523BFC4B5011D1A76C8B"]
% Which is not correct , as you see I have called the old function addHexNumber
% to do the addition
I believe the 2s complement is not applied correcttly in addHexNumber , what can I do to fix this problem?
Irwin2020
on 13 Dec 2018
Edited: Irwin2020
on 13 Dec 2018
function [ result ] = addHexNumber( hex1,hex2 )
% Clear the Command Windo everytime I click Run!
% hex1 = 'AA102FDE2FDEAA1012341234AAAAAEEDD6';
% hex2 = '2FDEAA10AA102FDE1234123401234FDEAA';
size = length(hex1);% how to include hex2 on this line?
result="";
carry = 0;
for i = size:-1:1
h1 =typecast(uint32(hex2dec(hex1(i))), 'int32');
h2 =typecast(uint32(hex2dec(hex2(i))), 'int32');
bothSum = h1 + h2+carry; %Each time through the loop the value of carry is added to h1and h2
if bothSum > 16
bothSum = bothSum - 16;
carry = 1;
end
add = dec2hex(typecast(bothSum, 'uint64')); % convert decimal 2 unsinged Hex int
result = result+add;
end
if carry ~=0 % is the addtion reminder not equal to zero ie 1
result = result+carry; % add the reminder (carry) to result
end
result=reverse(result); % Revered the answer so it can match the sum of orignal Hex value
end
James Tursa
on 13 Dec 2018
Edited: James Tursa
on 13 Dec 2018
The uint64 and int64 stuff is silly. You already know that the values are in the range 0-15, so what is the point of these conversions?
Irwin2020
on 13 Dec 2018
Any Idea on how to make both arrays iterate instead of just (hex1)?
size = length(hex1); % how to include hex2 on this line?
result="";
carry = 0;
for i = size:-1:1
h1 =typecast(uint64(hex2dec(hex1(i))), 'int64');
h2 =typecast(uint64(hex2dec(hex2(i))), 'int64');
James Tursa
on 13 Dec 2018
I'd like to back up a bit. Can you simply show us a variety of sample inputs and desired outputs? It is still not clear to me what all you want out of this discussion. Converting hex strings, integers, floating point numbers? To/From what? Etc.
Irwin2020
on 13 Dec 2018
is it alos possible to have cases for adding Hexs? like;
If they are both positive: Just add them together
If the larger one is negative, 1s compliment the positive one and subtract it. Then add 8 to the last hex (because you subtracted the sign bit)
If the smaller one is negative, 1s compliment the negative one and subtract it from the positive one
If they are both negative, add them together, except on the last hex subtract 8 (so you aren't adding the sign bit)
Can anyone please create these cases ?
Walter Roberson
on 13 Dec 2018
do not use hex2dec or any numeric representation . hex2dec converts to double precision . Your values overflow uint64.
Walter Roberson
on 13 Dec 2018
When you are dealing with 2's complement, the algorithm for subtraction is the same as adding the 2's complement of the subtrahend. Therefore you do not need any of those special cases: just add the values together in all those cases.
Walter Roberson
on 14 Dec 2018
Write your hex addition routine that works on the character elements without transforming into decimal . Then be consistent about representing in two's complement .
Note that two's complement requires either fixed width or else case analysis to determine whether to expand into more bytes.
Walter Roberson
on 17 Dec 2018
If you were using character vectors instead of strings, then consider
t(1) = dec2hex(hex1(end+1-1)) + dec2hex(hex2(end+1-1)
t(2) = dec2hex(hex1(end+1-2)) + dec2hex(hex2(end+1-2)
and so on. After which you have to process carry, then you convert back to hex, and finally reverse the order.
Reminder: Note that two's complement requires either fixed width or else case analysis to determine whether to expand into more bytes.
Irwin2020
on 19 Dec 2018
Also, I have created 10 Fs char to be used in the subtracting ( 2s complement ) step
Fs = ["FFFFFFFFFF"];
dec2hex(hex2dec(Fs)-hex2dec(extractBetween(RN(3),31,40))+1);
Walter Roberson
on 19 Dec 2018
Set carry to 0
Loop starting from the least significant digit (the end)
add the two corresponding hex positions and the carry. If the result is 15 or less set carry to 0, otherwise subtract 16 from the result and set carry to 1.
Continue looping towards more significant digits (the beginning)
After you have looped to add the most significant characters, if the carry is 0 then you are done. If the carry is not 0, then if you are working with unsigned values, extend your strings by a leading 1 (the carry.) If the carry is not zero and you are working with two's complement then you are done without having to extend the strings.
Number of digits at a time that need to be translated to decimal: at most 1. Not 10, not 40.
This is just standard addition logic in any base. When adding two values in any base, the maximum carry is always 1.
Walter Roberson
on 20 Dec 2018
hexval('A':'F') = 10:15;
hexval('a':'f') = 10:15;
hexval('0':'9') = 0:9;
Now
hexval(char(Fs))
looks up each hex byte into its decimal arithmetic without using hex2dec . It is translating only one byte at a time, so for example 'FF' would translate as [15 15] not as [255] . But I explained above why you only need one digit at a time.
hexval(char(Fs1)) + hexval(char(Fs2))
Now process carry from the last towards the beginning.
Irwin2020
on 20 Dec 2018
Edited: Irwin2020
on 20 Dec 2018
Thank you in advance for your answer, but again I still don’t understand this line above to be honest, is this gonna be insde the for-loop ?
and in this case , where I would put my register R ?
R is a 6 hex strings. and each string contains 40 chars
Thank you for your patience .
Walter Roberson
on 20 Dec 2018
hexval(char(Fs1)) + hexval(char(Fs2))
can be right before a for loop that handles carry.
Walter Roberson
on 20 Dec 2018
You posted
function [result] = Clockregister01(R,count)
clc
for j = 1:count
for i = 1:size(RN,1)-1
% RN(i,1:size(RN,2)) = addHexNumber(RN(i,1:size(RN,2)),RN(i+1,1:size(RN,2)))
A = addHexNumber(RN(i,:),RN(i+1,:));
end
end
result = RN;
end
You clear the command window in each call of the function, which is bad user interface.
You ovewrite A in each iteration.
You do not use the result A after you compute it.
You ignore your input R.
You use RN as if it is a variable, but you do not define it in this function and you do not pass it in.
Your code contains no documentation, so it is not possible to tell what the intended functionality is.
Irwin2020
on 20 Dec 2018
And no need for hex2dex anymore correct ? this will straight up adds the hex strings and if there will be a carry will go through the carry-for-loop right?
Also , this will prevent my result from getting overflows ? and return the same wedith of my string in this case 40 string chars?
Irwin2020
on 20 Dec 2018
"Continue looping towards more significant digits (the beginning)"....
is it gonna be the size of only hex1?
size = length(hex1);
for i = size:-1:1 ????
If this is true, what about the size of hex2? how I would write it in here? because I believe the original issue resides in the iteration of hex1 instead of the iteration of both hex1,hex2 and I didn't know how to fix it.
As far as the for loop that handles carry.I wrote this , which is similar to the old code
if bothHexSum <= 15
bothHexSum = bothHexSum - 16;
carry = 1;
end
Irwin2020
on 20 Dec 2018
Edited: Irwin2020
on 20 Dec 2018
function [ result ] = NaddHexNumber( hex1,hex2 )
size = length(hex1);
result="";
carry = 0;
for i = size:-1:1
% %
% where would the Sum of both hex goes?
% %
hexval(char(Fs1)) + hexval(char(Fs2))
bothHexSum = hex1 + hex2+carry;
carry = 0;
if bothHexSum <= 15
bothHexSum = bothHexSum - 16;
carry = 1;
end
add = bothHexSum;
result = result+add;
end
if carry ~=0
result = result+carry;
end
end
Walter Roberson
on 20 Dec 2018
Edited: Walter Roberson
on 20 Dec 2018
function [ result ] = NaddHexNumber( hex1,hex2 )
hexval('A':'F') = 10:15;
hexval('a':'f') = 10:15;
hexval('0':'9') = 0:9;
size = strlength(hex1);
bothHexSum = hexval(char(hex1)) + hexval(char(hex2))
for i = size:-1:2
if bothHexSum(i) > 15
bothHexSum(i) = bothHexSum(i) - 16;
bothHexSum(i-1) = bothHexSum(i-1) + 1;
end
end
if bothHexSum(1) > 15; bothHexSum(1) = bothHexSum(1) - 16; end
Now convert bothHexSum into hex.
Irwin2020
on 20 Dec 2018
I have converted the bothHexSum to hex without typecas it to uint', and in this case what Fs1 , Fs2 stand for? do you mean the Fs?
Thank you.
Answers (0)
See Also
Categories
Find more on Software Development Tools in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)