Files
flutterApp/lib/core/bluetooth/bytes_util.dart
2026-08-07 08:49:29 +08:00

39 lines
1.0 KiB
Dart

import 'dart:convert';
import 'dart:typed_data';
class BytesUtil {
static String bytesToHex(List<int> bytes) {
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join();
}
static Uint8List hexToBytes(String hex) {
hex = hex.replaceAll(' ', '').replaceAll('-', '');
if (hex.length % 2 != 0) hex = '0' + hex;
final bytes = Uint8List(hex.length ~/ 2);
for (int i = 0; i < hex.length ~/ 2; i++) {
bytes[i] = int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16);
}
return bytes;
}
static String bytesToString(List<int> bytes) {
try {
return utf8.decode(bytes);
} catch (_) {
return String.fromCharCodes(bytes);
}
}
static Uint8List stringToBytes(String str) {
return Uint8List.fromList(utf8.encode(str));
}
static List<int> toByteList(Uint8List data) {
return List<int>.from(data);
}
static String bytesToHexSpaced(List<int> bytes) {
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join(' ');
}
}