hexToBinary function

String? hexToBinary(
  1. String hexValue,
  2. int width
)

Convert a hex value string (e.g. "0x1a3f" or "1a3f") to binary (MSB-first).

Returns null if the input can't be parsed.

Implementation

String? hexToBinary(String hexValue, int width) {
  if (width <= 0) {
    return '';
  }

  var cleaned = hexValue.trim().toLowerCase();
  if (cleaned.startsWith('0x')) {
    cleaned = cleaned.substring(2);
  }
  if (cleaned.isEmpty) {
    return null;
  }

  final sourceWidth = cleaned.length * 4;
  final parseWidth = sourceWidth > width ? sourceWidth : width;
  try {
    return LogicValue.ofRadixString(
      "$parseWidth'h$cleaned",
    ).slice(width - 1, 0).toString(includeWidth: false);
  } on Exception {
    return null;
  }
}