Lua-根据字节和位信息生成字节流
1.代码
-- 定义参数配置表 local params_config = { -- 字节偏移 位偏移 位数 a = {byte_offset = 0, bit_offset = 0, length = 32}, -- 预留 b = {byte_offset = 4, bit_offset = 0, length = 3}, -- 预留 c = {byte_offset = 4, bit_offset = 3, length = 5} -- 预留 } -- 遍历params_config中的所有参数 for paramName, paramConfig in pairs(params_config) do paramConfig.byte_offset = paramConfig.byte_offset + 1 -- 增加1以适配lua的下标从1开始 print("初始化参数:", paramName) end -- 设置参数的函数 local function set_param(streamData, param_name, value) local param = params_config[param_name] if not param then print("未知参数,设置失败!") return nil, "Parameter not found" end local start_byte = param.byte_offset local start_bit = param.bit_offset local bit_length = param.length print("当前参数信息-字节偏移 位偏移 字节长度:", start_byte, start_bit, bit_length) -- 检查想要设置的值是否在允许的范围内 if value < 0 or value >= (1 << bit_length) then print("参数设置值溢出,设置失败!") return nil, "Value out of range" end -- 将想要设置的值设置到临时字节流中 local tempValue = value tempValue = value << start_bit -- 左移以适配参数的位起始位置 local tempParamTab = {0x00, 0x00, 0x00, 0x00} -- 处理的是32位整数 for i = 1, #tempParamTab do local byte = (tempValue >> ((i - 1) * 8)) & 0xFF -- 取出每个字节 tempParamTab[i] = byte end local tempString = "" for i = 1, #tempParamTab do tempString = tempString .. string.format("%02X ", tempParamTab[i]) end -- print(string.format("%02X", value), string.format("%02X", tempValue), tempString) -- 将临时字节流中的字节依次设置到最终的字节流中 for i = start_byte, start_byte+#tempParamTab-1 do streamData[i] = streamData[i] | tempParamTab[i-start_byte+1] end return true end -- 创建字节流 local streamData = {} -- 创建一个表来表示字节数据 for i = 1, 10 do streamData[i] = 0 -- 初始化每个字节为0 end -- 测试 set_param(streamData, "a", 65535) local hexString = "" for i = 1, #streamData do hexString = hexString .. string.format("%02X ", streamData[i]) end print("输出的字节流:", hexString) -- 输出: 1234AB CD... set_param(streamData, "b", 7) hexString = "" for i = 1, #streamData do hexString = hexString .. string.format("%02X ", streamData[i]) end print("输出的字节流:", hexString) -- 输出: 1234AB CD... set_param(streamData, "c", 31) hexString = "" for i = 1, #streamData do hexString = hexString .. string.format("%02X ", streamData[i]) end print("输出的字节流:", hexString) -- 输出: 1234AB CD...
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html