flutter 蓝牙开发 字节数组的使用

4个数 组成一个8位字节

  static int byte2222(int funcMode,int pumpMode,int brushMode,int cmdReSv){
    int byte;

    byte = funcMode | (pumpMode << 2) | (brushMode << 4) | (cmdReSv << 6);
    return byte;
  }
  
0 | (1 << 2) | (1 << 4) | (1 << 6) => 42

取二进制第几位数来计算 (一个字节藏了多个参数)

  static int byteUtils(int byteNum,int low,int high){
    //右移几位
    int shiftedNumber = byteNum >> low;  
    
    //8为二进制,不足补0
    String binaryString = shiftedNumber.toRadixString(2).padLeft(8, '0');
      
    // 截取一段二进制,位数为 high - low
    String lowBits = binaryString.substring(8-(high - low), 8);

    // 截取一段二进制转成10进制
    int lowInt = int.parse(lowBits, radix: 2);

    return lowInt;
  }


byteUtils(42, 2, 4) => 2
00101010 

字节数组转16进制数组 (蓝牙数据转16进制)

  static  List<String> byte16(List<int> array){
     List<String> hexArray = array.map((byte) => byte.toRadixString(16)).toList();
     // print("bytes hexArray:    ${array.length}  ${hexArray.length} $hexArray");
    return hexArray;
  }

字节转int(1,2,4,8字节转成int)

import 'dart:typed_data';
  

//一个字节转int
  static int byteInt8(
    List<int> byte,
  ) {
    Uint8List byteArray = Uint8List.fromList(byte); // 字节数组

    //目前小端
    int value =
        byteArray.buffer.asByteData().getInt8(0); // 从字节数组中读取一个32位整数(大端序)

    return value;
  }
  
//两个字节转int
  static int byteInt16(List<int> byte, {bool little = true}) {
    Uint8List byteArray = Uint8List.fromList(byte); // 字节数组

    //目前小端
    int value = byteArray.buffer.asByteData().getInt16(
        0, little ? Endian.big : Endian.little); // 从字节数组中读取一个32位整数(大端序)

    return value;
  }
  
  //四个字节转int
  static int byteInt32(List<int> byte, {bool little = true}) {
    Uint8List byteArray = Uint8List.fromList(byte); // 字节数组

    //目前小端
    int value = byteArray.buffer.asByteData().getInt32(
        0, little ? Endian.big : Endian.little); // 从字节数组中读取一个32位整数(大端序)

    return value;
  }
  
  //八个字节转int
  static int byteInt64(List<int> byte, {bool little = true}) {
    Uint8List byteArray = Uint8List.fromList(byte); // 字节数组

    //目前小端
    int value = byteArray.buffer.asByteData().getInt64(
        0, little ? Endian.big : Endian.little); // 从字节数组中读取一个32位整数(大端序)

    return value;
  }

int转字节(int转成1,2,4,8字节)

import 'dart:typed_data';

//int转成一个字节      
  static Uint8List intByte8(int value, {bool little = true}) {
    ByteData byteData = ByteData(1); // 创建一个包含1个字节的ByteData对象

    byteData.setInt8(0, value); // 将整数写入字节数据(大端序)

    Uint8List bytes = byteData.buffer.asUint8List(); // 将ByteData对象转换为Uint8List

    return bytes;
  }


  static Uint8List intByte16(int value, {bool little = true}) {
    ByteData byteData = ByteData(2); // 创建一个包含2个字节的ByteData对象

    byteData.setInt16(
        0, value, little ? Endian.big : Endian.little); // 将整数写入字节数据(大端序)

    Uint8List bytes = byteData.buffer.asUint8List(); // 将ByteData对象转换为Uint8List

    return bytes;
  }


  
  static Uint8List intByte(int value, {bool little = true}) {
    ByteData byteData = ByteData(4); // 创建一个包含4个字节的ByteData对象

    byteData.setInt32(
        0, value, little ? Endian.big : Endian.little); // 将整数写入字节数据(大端序)

    Uint8List bytes = byteData.buffer.asUint8List(); // 将ByteData对象转换为Uint8List

    return bytes;
  }


  static Uint8List intByte64(int value, {bool little = true}) {
    ByteData byteData = ByteData(8); // 创建一个包含4个字节的ByteData对象

    byteData.setInt64(
        0, value, little ? Endian.big : Endian.little); // 将整数写入字节数据(大端序)

    Uint8List bytes = byteData.buffer.asUint8List(); // 将ByteData对象转换为Uint8List

    return bytes;
  }

字节转double(4字节转成double)

  static String byteString(List<int> byte) {
    // 模拟从蓝牙接收到的 4 字节 float 类型数据
  List<int> bluetoothBytes = [0x40, 0x48, 0xF5, 0xC3];

  // 将字节数据转换为 ByteData
  ByteData byteData = ByteData.view(Uint8List.fromList(bluetoothBytes).buffer);

  // 读取 float 数据,这里假设是大端字节序
  double floatValue = byteData.getFloat32(0, Endian.big);

return floatValue ;
  }

字节数据转成String

  static String byteString(List<int> byte) {
    String str = String.fromCharCodes(byte);
    return str;
  }

String转成字节数据,可以限定长度(把String转成字节数组)

  static List<int> utf8WithString(String str,{int len = 128}) {
    // 将字符串编码为UTF-8
    List<int> bytes = utf8.encode(str);

    // 创建一个长度为128字节的列表,用0填充
    List<int> paddedBytes = List.filled(len, 0);

    // 将编码后的字节数据复制到填充列表中
    for (var byte in bytes) {
      if (paddedBytes.indexOf(0) < len) {
        paddedBytes[paddedBytes.indexOf(0)] = byte;
      }
    }

    return paddedBytes;
  }
### 关于 VSCode 中进行 Flutter 蓝牙开发 在 VSCode 中进行 Flutter蓝牙开发,主要涉及以下几个方面: #### 1. **环境搭建** 为了在 VSCode 中进行 Flutter 开发,首先需要安装并配置好 Flutter 和 Dart 插件。确保已正确设置 `flutter` 命令行工具,并通过以下命令验证版本: ```bash flutter --version ``` 对于蓝牙开发,通常会依赖第三方库来实现跨平台支持。常用的库有 [`flutter_blue_plus`](https://pub.dev/packages/flutter_blue_plus),它是一个功能强大的 Bluetooth LE 库。 #### 2. **示例代码:扫描附近设备** 以下是基于 `flutter_blue_plus` 实现的一个简单的蓝牙设备扫描示例: ```dart import 'package:flutter/material.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: BluetoothPage(), ); } } class BluetoothPage extends StatefulWidget { @override _BluetoothPageState createState() => _BluetoothPageState(); } class _BluetoothPageState extends State<BluetoothPage> { final FlutterBluePlus flutterBlue = FlutterBluePlus.instance; List<ScanResult> scanResults = []; void startScanning() async { setState(() { scanResults.clear(); // 清除之前的扫描结果 }); flutterBlue.startScan(timeout: Duration(seconds: 4)); var subscription = flutterBlue.scanResults.listen((results) { for (var result in results) { if (!scanResults.contains(result)) { setState(() { scanResults.add(result); }); } } }); await Future.delayed(Duration(seconds: 5)); await flutterBlue.stopScan(); subscription.cancel(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('BLE 设备扫描')), body: Column( children: [ ElevatedButton( onPressed: () => startScanning(), child: Text('开始扫描'), ), Expanded( child: ListView.builder( itemCount: scanResults.length, itemBuilder: (context, index) { ScanResult r = scanResults[index]; return ListTile( title: Text(r.device.name ?? "未知设备"), subtitle: Text('${r.rssi} dBm'), ); }, ), ) ], ), ); } } ``` 上述代码展示了如何使用 `flutter_blue_plus` 进行蓝牙设备的扫描操作[^4]。 #### 3. **注意事项** - 如果涉及到 Android 平台上的特定需求(如跳转至原生页面),可以参考混合开发相关内容[^2]。 - 对于复杂的业务逻辑,可能需要开发自定义插件以桥接 Dart 和 Native 功能[^3]。 #### 4. **调试技巧** 在 VSCode 中可以通过断点调试、日志打印等方式排查问题。建议开启详细的日志记录以便分析蓝牙通信中的异常情况: ```dart await FlutterBluePlus.setLogLevel(LogLevel.verbose); ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值