flutter 整型(int)与16进制字符(hex)相互转换

2020-12-30  本文已影响0人  微风_10a5

话不多说,直接进入正题

  //int ---> hex
  String _intToHex(int num) {
    String hexString = num.toRadixString(16);
    return hexString;
  }

推荐使用_hexToInt2方法转换

  //hex ---> int  更简单,加上了容错处理(感谢 @"坐了整个春夏秋冬" 小伙伴的反馈)
  int? _hexToInt2(String hex) {
    int? val;
    if(hex.toUpperCase().contains("0X")){
      String desString = hex.substring(2);
      val = int.tryParse("0x$desString");
    }else {
      val = int.tryParse("0x$hex");
    }
    return val;
  }
 //hex ---> int
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }
 //int ---> 指定长度的hex (如指定长度为6的情况,0x000001 0x001234, 0xefab23)
  String _intToFormatHex(int num) {
    String hexString = num.toRadixString(16);
    print("hexString=$hexString");
    String formatString = hexString.padLeft(6, "0");
    print("formatHexString=$formatString");
    return formatString;
  }

点击一下floatingActionButton,测试结果如下:


image.png

完整代码如下:

import 'package:flutter/material.dart';
// import 'package:flutter_app_log_test/zz_log.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("widget.title"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          String a = _intToHex(998);
          int b = _hexToInt(a);

          int k = int.parse("0x" +a);
          print("a=$a");
          print("b=$b");
          print("k=$k");

          String c = _intToFormatHex(998);
          print("c=$c");

          print("-----------下面是_hexToInt2---------------");
          int? i = _hexToInt2("0x" +a);
          print("i=$i");

          int? n = _hexToInt2("0X" +a);
          print("n=$n");

          int? p = _hexToInt2("0Xx22222" +a);
          print("p=$p");

        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  //int ---> hex
  String _intToHex(int num) {
    String hexString = num.toRadixString(16);
    return hexString;
  }

  //hex ---> int
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }


  //hex ---> int  更简单,加上了容错处理(感谢 @"坐了整个春夏秋冬" 小伙伴的反馈)
  int? _hexToInt2(String hex) {
    int? val;
    if(hex.toUpperCase().contains("0X")){
      String desString = hex.substring(2);
      val = int.tryParse("0x$desString");
    }else {
      val = int.tryParse("0x$hex");
    }
    return val;
  }

  //int ---> 指定长度的hex (如指定长度为6的情况,0x000001 0x001234, 0xefab23)
  String _intToFormatHex(int num) {
    String hexString = num.toRadixString(16);
    print("hexString=$hexString");
    String formatString = hexString.padLeft(6, "0");
    print("formatHexString=$formatString");
    return formatString;
  }
}


结尾

今天的分享先到这里了,后续会分享更多的干货,欢迎点赞,加关注了,祝君好运!!

上一篇下一篇

猜你喜欢

热点阅读