octal to binary, flip the binary, convert to hex

5 Ansichten (letzte 30 Tage)
Adam Kaas
Adam Kaas am 5 Jun. 2014
Bearbeitet: Joseph Cheng am 5 Jun. 2014
I have a unique situation where I must take an octal label (e.g., '52') and ultimately arrive at a hex value that happens to be the flipped version of the binary of the octal. Poor wording... I know. Here is an example:
Octal label = 52
Binary of octal 52 = 00101010
Flipped binary of octal 52 = 01010100
Hex of flipped binary of octal 52 = 54
I have 78 different octal numbers I may have to do this for and am looking for a simple solution. The complicated part for me is the fact that MATLAB drops off the leading zeroes, so using fliplr() doesn't help too much when trying to flip the binary number. Here is what I have so far:
for i = 1:length(chosenLabels)
chosenLables(i) = bin2hex(fliplr(dec2bin(base2dec(chosenLabels(i), 8))));
end
This is how I found out bin2hex isn't a function :) And as I said, I know the fliplr isn't going to work. Ideally, one line of code would be awesome but I'm guessing I may need to use a for loop and create a binary vector that includes the leading zeroes.

Akzeptierte Antwort

Joseph Cheng
Joseph Cheng am 5 Jun. 2014
Bearbeitet: Joseph Cheng am 5 Jun. 2014
You can try something like this
octstr = ['52';'51']; %your oct inputs
bin_str = dec2bin(base2dec(octstr,8),8) %convert to decimal using base 8 and 8 indexes long.
bin_str=bin_str(:,end:-1:1) %reverse the binary
hexstr = dec2hex(bin2dec(bin_str)) %convert bin->dec->hex
and you don't even need a for loop!
  4 Kommentare
Joseph Cheng
Joseph Cheng am 5 Jun. 2014
Bearbeitet: Joseph Cheng am 5 Jun. 2014
So you're saying the octal number is not a string but an octal number written as a decimal number?
then you can do this.
clc,clear all;
octdouble = [46 46 23 35 5 4 32 47 57];
octstr = num2str(octdouble')
octstr(octstr==' ')='0'
bin_str = dec2bin(base2dec(octstr,8),8)
bin_str=bin_str(:,end:-1:1)
hexstr = dec2hex(bin2dec(bin_str))
Joseph Cheng
Joseph Cheng am 5 Jun. 2014
Bearbeitet: Joseph Cheng am 5 Jun. 2014
you don't need to ' ' to '0' substitution. got a random error but that was because i was using a random integer generator to make the octals and didn't notice i had 8 and 9 in in there which wouldn't be a valid octal number, duh.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by