Hexadecimal to Binary Conversion: MATLAB vs. Python

This article demonstrates how to convert hexadecimal numbers to binary representations using both MATLAB and Python. The core functionality is achieved with the Hex2Bin function in both languages, showcasing their respective approaches and syntax.

MATLAB Implementation:

function s= Hex2Bin(h,N)
    h=h(:);  % Make sure h is a column vector.
    if iscellstr(h), h = char(h); end
    if isempty(h), s = []; return, end
    % Work in upper case.
    h = upper(h);
    [m,n]=size(h);
    % Right justify strings and form 2-D character array.
    if ~isempty(find((h==' ' | h==0),1))
      h = strjust(h);
      % Replace any leading blanks and nulls by 0.
      h(cumsum(h ~= ' ' & h ~= 0,2) == 0) = '0';
    else
      h = reshape(h,m,n);
    end
    % Check for out of range values
    if any(any(~((h>='0' & h<='9') | (h>='A'&h<='F'))))
       error('MATLAB:hex2bin:IllegalHexadecimal',...
          'Input string found with characters other than 0-9, a-f, or A-F.');
    end
    sixteen = 16;
    p = fliplr(cumprod([1 sixteen(ones(1,n-1))]));
    p = p(ones(m,1),:);
    s = h <= 64; % Numbers
    h(s) = h(s) - 48;
    s =  h > 64; % Letters
    h(s) = h(s) - 55;
    s = sum(h.*p,2);
    % Decimal  to Binary 
    d = s;
    n = N;
    d = double(d);
    if nargin<2
        n=1; % Need at least one digit even for 0.
    else
        if ~(isnumeric(n) || ischar(n)) || ~isscalar(n) || n<0
            error('MATLAB:hex2bin:InvalidBitArg','N must be a positive scalar numeric.');
        end
        n = round(double(n)); % Make sure n is an integer.
    end;
    % Actual algorithm
    [f,e] = log2(max(d)); % How many digits do we need to represent the numbers?
    s = char(rem(floor(d*pow2(1-max(N,e):0)),2)+'0');
end

Python Implementation:

def Hex2Bin(h, N):
    h = h.strip()  # Remove leading and trailing whitespaces
    h = h.upper()  # Convert to uppercase
    if len(h) == 0:
        return ''  # Return empty string if input is empty

    # Check for out of range values
    for char in h:
        if not (char.isdigit() or (char >= 'A' and char <= 'F')):
            raise ValueError('Input string found with characters other than 0-9, a-f, or A-F.')

    # Convert hexadecimal to decimal
    d = int(h, 16)

    # Convert decimal to binary
    n = int(N)
    if n < 0:
        raise ValueError('N must be a positive scalar numeric.')

    binary = bin(d)[2:]  # Convert decimal to binary string
    binary = binary.zfill(n)  # Pad with leading zeros if necessary

    return binary

Explanation:

  • MATLAB: The MATLAB implementation involves several steps: converting the hexadecimal string to a numeric array, performing base conversion from hexadecimal to decimal, and then converting the decimal value to binary using bitwise operations.
  • Python: The Python code leverages the built-in int(h, 16) function for hexadecimal to decimal conversion and the bin(d)[2:] function for decimal to binary conversion. Error handling ensures valid input and appropriate output formatting.

Usage Example:

Both MATLAB and Python functions can be used with the following input:

hex_string = 'FF'  # Hexadecimal input
num_bits = 8  # Desired number of bits

# MATLAB
matlab_binary = Hex2Bin(hex_string, num_bits)

# Python
python_binary = Hex2Bin(hex_string, num_bits)

# Output:
matlab_binary = '11111111'
python_binary = '11111111'

Both functions produce the same binary output: '11111111'.

In conclusion, this article provides a comprehensive comparison of hexadecimal to binary conversion approaches in MATLAB and Python, highlighting the advantages and differences in their respective implementations.

Hexadecimal to Binary Conversion in MATLAB and Python

原文地址: https://www.cveoy.top/t/topic/qFGO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录