How do I convert a string into its binary equivalent?

조회 수: 7 (최근 30일)
raktim banerjee
raktim banerjee 2011년 1월 24일
I want to convert 2 strings (user_id & password) in binary equivalent and then concatenate these binary string. So that later i can get back both string separately. Both strings are 20 character long each. If less than 20 character then '*' will be appended to the strings.
I wrote this. But it does not work. Please tell me how it can be done?
user_id = 'banerjee.raktim';
password = '123456789';
len_id = length(user_id);
len_pwd = length(password);
if len_id < 20
x = 20 - len_id;
for i = 1:x,
user_id = [ user_id '*'];
end
end
if len_pwd < 20
x = 20 - len_pwd;
for i = 1:x,
password = [password '*'];
end
end
user_id = double(user_id);
user_id = dec2bin(user_id);
save user_id;
password = double(password);
password = dec2bin(password);
save password;
user_id_final = '0';
password_final = '0';
for i = 1:20,
t = user_id(i,:);
len_t = length(t);
diff = 8 - len_t;
for j = 1:diff,
t = ['0' t];
end
user_id_final = [user_id_final t];
end
save user_id_final;
for i = 1:20,
t = password(i,:);
len_t = length(t);
diff = 8 - len_t;
for j = 1:diff,
t = ['0' t];
end
password_final = [password_final t];
end
user_id_final(1) = [];
password_final(1) = [];
watermark= [user_id_final password_final];
save watermark;

채택된 답변

Walter Roberson
Walter Roberson 2011년 1월 24일
user_id = 'banerjee.raktim';
password = '123456789';
user_id = [user_id repmat('*',1,20)];
user_id = user_id(1:20);
password = [password repmat('*',1,20)];
password = password(1:20);
userid_final = reshape(dec2bin(user_id,8),1,[]);
password_final = reshape(dec2bin(password,8),1,[]);
watermark = [userid_final password_final];
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 1월 25일
You will have to reshape() the watermark before you bin2dec it.
Also, I just noticed a correction to make my code match yours:
userid_final = reshape(dec2bin(user_id,8).',1,[]);
password_final = reshape(dec2bin(password,8).',1,[]);
Each of the dec2bin would produce a 20x8 bit matrix, and the original reshape would have flattened that along the *columns*, whereas your code had them flattened along the *rows. The .' (transpose) that I show in this comment will cause my version to be flattened along the rows like yours was.
The implication is that you should
char(bin2dec(reshape(watermark, 8, []).'))
raktim banerjee
raktim banerjee 2011년 1월 25일
Thank you Sir a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by