The goal is to change a = [0 0 0 1 0 0 0 0] binary array to decimal value
Create a new function, copy and paste the code into it to save
function [ y ] = bit2hex(x ,dir)
% 8位二进制数转换成 十进制数
% y为hex十进制输出,x为输入的8位二进制数组
% d7 d6 d5 d4 d3 d2 d1 d0
% dir = 1(高位是d0,低位是d7)
% = 0(高位是d7,低位是d0)
y = 0;
for i = 1:8
if( dir == 1)
y = y + x(i)*2^(i-1) ;
else
y = y + x(i)*2^(8-i);
end
end
end
After saving, the name must be the same as the function name, without Chinese name
a is the array that needs to be transformed, b is the decimal save parameter d0d1d2d3d4d5d6d7 when dir=1; when dir=0 is the familiar order d7d6d5d4d3d2d1d0
Sometimes truncated head or tail (sign bit) is used
function [ y ] = bit2hex(x ,dir,HeadOrEnd)
% 8位二进制数转换成 十六进制数
% y为hex十六进制输出,x为输入的8位二进制数组
% d7 d6 d5 d4 d3 d2 d1 d0
% dir = 1(高位是d0,低位是d7)
% = 0(高位是d7,低位是d0)
% HeadOrEnd=1 把第一位截断(赋值为0即可)
% =0 把最后一位截断
y = 0;
if(HeadOrEnd == 1)
x(1)=0;
else
x(8)=0;
end
for i = 1:8
if( dir == 1)
y = y + x(i)*2^(i-1) ;
else
y = y + x(i)*2^(8-i);
end
end
if(dir==0 && HeadOrEnd==0) || (dir==1 && HeadOrEnd==1)
y=y/2;
end
Note that this truncated high/low bit will be shifted to the right (dividing an integer by 2 means shifting to the right by 1 bit)
The same is low