binary addition for 128 bit

I want to addition to 128binary bit represent in char.

2 comentarios

Geoff Hayes
Geoff Hayes el 17 de En. de 2015
Radwa - please clarify your statement. Do you have two 128 character strings of ones and zeros that you wish to add as if they were 128-bit integers? If so, are the integers signed or unsigned? What algorithm are you using to implement this?
Radwa
Radwa el 17 de En. de 2015
I have 64 binary bits in form of 1*64 char I want to add 1 to it

Iniciar sesión para comentar.

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 17 de En. de 2015

1 voto

Radwa - try the following. There could be more efficient algorithms, but this is pretty straightforward. Just save all of the code to a file named binaryAdd.m.
function [sRes] = binaryAdd(s1,s2)
numBits = 64;
% ensure that the strings are the correct size
s1 = validateBits(s1,numBits);
s2 = validateBits(s2,numBits);
% add the two strings together
sRes = repmat('0',1,numBits);
% indicator for a remainder
haveRem = 0;
% iterate over each bit (assume that right-most bit is least significant bit)
for k = numBits:-1:1
% sum the kth bits
v = str2double(s1(k)) + str2double(s2(k)) + haveRem;
haveRem = 0;
% ignore case of the sum being zero, need only check for 1, 2, or 3
if v==1
sRes(k) = '1';
elseif v>1
sRes(k) = num2str(mod(v,2));
haveRem = 1;
end
end
if haveRem
sRes = [repmat('0',1,numBits-1) '1' sRes];
end
end
function [s] = validateBits(s,numBits)
if length(s)>numBits
s = s(1:numBits);
elseif length(s)<numBits
s = [repmat('0',1,numBits-length(s)) s];
end
end
For your example,
binaryAdd(repmat('1',1,64),'1')
the result is a 128-bit string
ans =
00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000

4 comentarios

Radwa
Radwa el 17 de En. de 2015
thanks , what can I do If I want to add 1 to the 128 bit ( I want to put the one in the most significant bit)
Geoff Hayes
Geoff Hayes el 17 de En. de 2015
If the most significant bit is zero and you add one to it, then the zero changes to a one. If the most significant bit is a one and you add a one to it, then what should happen? Should the result roll over? Should the result now be 256 bits? Should the value stay the same?
Radwa
Radwa el 17 de En. de 2015
Mu idea that I have counter with length 64 bit ( 1*64 char) I want to add 1 in every iteration in the counter and if reach the maximum all of them is 1 I want to begin from all zeros
Radwa
Radwa el 17 de En. de 2015
yes I want to have the same shape or that shape counter= {' '88' '99' 'aa' 'bb' 'cc' 'dd' 'ee' 'ff'};

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 16 de En. de 2015

Comentada:

el 17 de En. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by