이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
Please help me create Decimal to Two's Complement/ Two's Complement to Decimal function without using the built-in function in Matlab
조회 수: 7 (최근 30일)
이전 댓글 표시
Irwin2020
2018년 12월 10일
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
James Tursa
2018년 12월 10일
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
2018년 12월 11일
편집: Irwin2020
2018년 12월 12일
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
2018년 12월 11일
편집: James Tursa
2018년 12월 11일
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
2018년 12월 11일
편집: Irwin2020
2018년 12월 11일
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
2018년 12월 11일
편집: Walter Roberson
2018년 12월 11일
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
2018년 12월 12일
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
2018년 12월 12일
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
2018년 12월 12일
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
2018년 12월 12일
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
2018년 12월 13일
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
2018년 12월 13일
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
2018년 12월 13일
편집: Irwin2020
2018년 12월 20일
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
2018년 12월 13일
편집: Irwin2020
2018년 12월 13일
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
2018년 12월 13일
편집: James Tursa
2018년 12월 13일
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
2018년 12월 13일
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
2018년 12월 13일
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
2018년 12월 13일
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
2018년 12월 13일
do not use hex2dec or any numeric representation . hex2dec converts to double precision . Your values overflow uint64.
Walter Roberson
2018년 12월 13일
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
2018년 12월 14일
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
2018년 12월 17일
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
2018년 12월 19일
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
2018년 12월 19일
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
2018년 12월 20일
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
2018년 12월 20일
편집: Irwin2020
2018년 12월 20일
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
2018년 12월 20일
hexval(char(Fs1)) + hexval(char(Fs2))
can be right before a for loop that handles carry.
Walter Roberson
2018년 12월 20일
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
2018년 12월 20일
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
2018년 12월 20일
"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
2018년 12월 20일
편집: Irwin2020
2018년 12월 20일
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
2018년 12월 20일
편집: Walter Roberson
2018년 12월 20일
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
2018년 12월 20일
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.
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- 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)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)