bin2Hex method

String bin2Hex(
  1. Uint8List bytes
)

Implementation

String bin2Hex(Uint8List bytes) {
  // Allocate memory for the hexadecimal representation
  final hexMaxLen = bytes.length * 2 + 1;
  final hexPointer = calloc<ffi.Char>(hexMaxLen);
  final binPointer = calloc<ffi.Uint8>(bytes.length);

  // Copy the binary data into the allocated buffer
  for (var i = 0; i < bytes.length; i++) {
    binPointer.elementAt(i).value = bytes[i];
  }

  // Convert binary data to hexadecimal
  final result = sodium_bin2hex(
    hexPointer,
    hexMaxLen,
    binPointer.cast<ffi.UnsignedChar>(),
    bytes.length,
  );

  List<int> output = [];
  if (result != ffi.nullptr) {
    for (var i = 0; i < hexMaxLen - 1; i++) {
      output.add(result[i]);
    }
  } else {
    debugPrint('[Lazysodium] Conversion bin2Hex failed.');
  }

  // Free allocated memory for hexPointer
  calloc.free(binPointer);
  calloc.free(hexPointer);

  return String.fromCharCodes(output.toList());
}