フィルターのクリア

how to change or compliment a particular bit in the binary string?

5 ビュー (過去 30 日間)
Mudasir Ahmed
Mudasir Ahmed 2016 年 10 月 25 日
コメント済み: Image Analyst 2016 年 10 月 25 日
Hi
I have number like a=50 I want to convert it to binary, then I want to randomly choose the position in a binary string and compliment it Like
a=50
b=dec2bin(a)
b=110010
e.g position=4
b becomes
b=110110
how I perform this. kindly help me

採用された回答

KSSV
KSSV 2016 年 10 月 25 日
a=50 ;
b=dec2bin(a) ;
b1=110010 ;
b=str2double(regexp(num2str(b),'\d','match')) ;
pos = 4 ;
b(pos) = 1 ;
% join the numbers
iwant=str2double(sprintf('%1d',b)) ;
  3 件のコメント
Guillaume
Guillaume 2016 年 10 月 25 日
編集済み: Guillaume 2016 年 10 月 25 日
And change the call to dec2bin to output 8 bits instead of just the minimum and the answer is broken because position is defined wrongly.
Also, a simpler way to convert that string of '0' and '1' to number would be:
b = dec2bin(a); %change it to dec2bin(a, 8) and the whole thing is broken
b = b - '0'; %no need for expensive regexp or str2double
But of course, you may as well not bother and just change the character:
b = dec2bin(a);
b(pos) = '1';
Finally, note that this does not flip a bit, just sets it to 1.
Massimo Zanetti
Massimo Zanetti 2016 年 10 月 25 日
This is quite tricky...

サインインしてコメントする。

その他の回答 (2 件)

Guillaume
Guillaume 2016 年 10 月 25 日
Note that in your example b is not 110010 but '110010'. The difference is important, b is an array of character, not a number.
Also note that your usage of position is very unconventional. Usually the bits are numbered from right to left (LSB to MSB) not left to right. This is important because if your represent a with 8 bit, 00110010, with your convention position 4 is a different bit.
Anyway, the simplest way to flip a bit in a number is not to convert it to binary, but simply use bitget and bitset:
a = 50;
bittoflip = 3; %Using normal convention, not yours, bit 3 is the 3rd rightmost
flippeda = bitset(a, bittoflip, ~bitget(a, bittoflip))
You can easily check that it's done the deed:
>> dec2bin(a)
ans =
110010
>> dec2bin(flippeda)
ans =
110110
  2 件のコメント
Mudasir Ahmed
Mudasir Ahmed 2016 年 10 月 25 日
thank you so much sir
Image Analyst
Image Analyst 2016 年 10 月 25 日
For what it's worth, bitset() was what I thought of also. (+1 vote)

サインインしてコメントする。


Massimo Zanetti
Massimo Zanetti 2016 年 10 月 25 日
Here it is
a=50;
b=dec2bin(a)
pos = 4;
b(pos) = char(97-double(b(pos)))

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by