MATLAB: Octal to binary, flip the binary, convert to hex

binaryhexoctal

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.

Best Answer

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!