十六进制转Ascii,长度计数加倍

问题描述 投票:0回答:1

当我将十六进制值转换为 ASCII 并将 ASCII 传递到文本字段时,它使文本长度加倍。下面是我使用的转换,如果您从屏幕截图中看到,两个文本字段的总字符数都是 16,但显示为 32。我可以知道为什么长度加倍吗? enter image description here

String hexToAscii(String hexString) => List.generate(
        hexString.length ~/ 2,
        (i) => String.fromCharCode(
            int.parse(hexString.substring(i * 2, (i * 2) + 2), radix: 16)),
      ).join();

// 添加文本字段

final modelController = TextEditingController();
modelController.text = hexToAscii(tempData[0]); // Passing Data. I used your method in place of hexToAscii method. No Change

    _buildExpandableContent(int selectedENPIndex) {
List<Widget> columnContent = [];

for (int i = 0; i < namePlates[selectedENPIndex].contents.length; i++) {
  TextEditingController dynamicController = TextEditingController();

  //var allowedCharacters = 'r\'^[a-zA-Z0-9. ]*\'';
  var allowedCharacters = namePlates[selectedENPIndex].acceptingString[i];
  //print("Allowed Characters: $allowedCharacters");

  var allowedRegEx = RegExp(escape(allowedCharacters));
  //print("Allowed RegEx: $allowedRegEx");
  if (selectedENPIndex == 0) {
    if (namePlates[selectedENPIndex]
            .contents[i]
            .replaceAll(RegExp('[^A-Za-z0-9]'), '')
            .toLowerCase() ==
        ENPTextFieldNames.model.name) {
      dynamicController = modelController;
    } 
  }



  columnContent.add(Container(
    padding: const EdgeInsets.only(left: 50, right: 50, bottom: 10),
    child: TextFormField(
      enableInteractiveSelection: false,
      maxLength: selectedENPIndex == 2 ? 24 : 16,
      // autofocus: true,
      cursorColor: _selectedTheme.primaryColorDark,

      // inputFormatters: <TextInputFormatter>[
      //   FilteringTextInputFormatter.allow(RegExp(allowedCharacters))
      // ],
      onChanged: (value) {
        checkRegEx();
        _selectedField = dynamicController;
      },
      controller: dynamicController,
      validator: (value) {
        if (value == null || value.trim().isEmpty) {
          return "Please enter ${namePlates[selectedENPIndex].contents[i]}";
        }
        return null;
      },
      decoration: InputDecoration(
          border: UnderlineInputBorder(
              borderSide:
                  BorderSide(color: _selectedTheme.primaryColorDark)),
          enabledBorder: UnderlineInputBorder(
              borderSide:
                  BorderSide(color: _selectedTheme.primaryColorDark)),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                  color: _selectedTheme.primaryColorDark, width: 2)),
          labelText: namePlates[selectedENPIndex].contents[i],
          hintText: namePlates[selectedENPIndex].acceptingString[i],
          labelStyle: TextStyle(color: _selectedTheme.primaryColorDark)),
    ),
  ));
}
columnContent.add(const Padding(
  padding: EdgeInsets.only(top: 20, bottom: 20),
));

return columnContent;

} enter image description here //飞镖垫

void main() {
 var hexString = "004D006F00640065006C0020004D006F00640065006C0020004D006F00640065";
  
  print(hexToAscii(hexString)); // Output is Model Model Mode
  print(hexToAscii(hexString).length); // Output is 32, this should be 16. Attached the Dart Pad screenshot 
}


String hexToAscii(String hexString) => List.generate(
        hexString.length ~/ 2,
        (i) => String.fromCharCode(
            int.parse(hexString.substring(i * 2, (i * 2) + 2), radix: 16)),
      ).join();
flutter dart hex ascii
1个回答
0
投票

您面临的问题可能是由于 ASCII 字符串中存在空字符

(i.e., \u0000)

这些空字符通常在

UTF-16
编码中用作填充,并且在 Dart 中作为字符串处理时可能会导致文本长度加倍。

您可以通过在将十六进制字符串转换为

ASCII
后过滤掉空字符并确保转换过程正确处理输入字符串来改进 hexToAscii 函数。

这应该适合你。

String hexToAscii(String hexString) {
  // Convert hex string to ASCII, then remove null characters
  return List.generate(
    hexString.length ~/ 4, // Using ~/4 for UTF-16 (each char is 4 hex digits)
    (i) {
      var charCode = int.parse(hexString.substring(i * 4, (i * 4) + 4), radix: 16);
      return String.fromCharCode(charCode);
    },
  ).join().replaceAll('\u0000', '');
}

或者,您可以使用

dart:convert
包。

import 'dart:convert';
import 'dart:typed_data';

void main() {
  var hexString = "004D006F00640065006C0020004D006F00640065006C0020004D006F00640065";

  print(hexToAscii(hexString)); // Output should be "Model Model Model"
  print(hexToAscii(hexString).length); // Output should be 15
}

String hexToAscii(String hexString) {
  Uint8List bytes = hexStringToBytes(hexString);
  String asciiString = utf8.decode(bytes, allowMalformed: true);
  return asciiString.replaceAll('\u0000', '');
}

Uint8List hexStringToBytes(String hexString) {
  List<int> bytes = [];
  for (int i = 0; i < hexString.length; i += 4) {
    String byteString = hexString.substring(i, i + 4);
    int byte = int.parse(byteString, radix: 16);
    bytes.add(byte >> 8);
    bytes.add(byte & 0xFF);
  }
  return Uint8List.fromList(bytes);
}

© www.soinside.com 2019 - 2024. All rights reserved.