从2字节大字节序(motorola)字节数组中提取12位整数

时间:2020-01-14 10:31:11

标签: python bit-manipulation micropython

我正在尝试提取2字节(16位)消息中最多占12位的整数,该消息采用big-endian格式。我已经进行了一些研究,并期望我必须使用bit_manipulation(位移)来实现这一目标,但是我不确定如何将其应用于big-endian格式。

这里有几个答案使用了python'Numpy'包,但是我无法在Micropython上访问它。我确实可以访问“ ustruct”模块,该模块用于解压缩消息的某些其他部分,但它似乎仅适用于8位,16位和32位消息。

到目前为止,我唯一想到的是:

int12 = (byte1 << 4) + (byte2)
expected_value = int.from_bytes(int12)

但是这并没有给我我期望的数字。例如0x02,0x15应该使用小数533。 我要去哪里错了?

我是位操作和从字节提取数据的新手,非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这应该有效:

        WebRequest request = WebRequest.Create("WebServiceUrl");
        request.Method = "POST";
        WebResponse response = null;
        try
        {
            response = request.GetResponse();
        }
        catch(WebException exception)
        {
            using (response = exception.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                {
                    string text = new StreamReader(data).ReadToEnd();
                    Console.WriteLine(text);
                    Console.ReadLine();
                }
            }
            Console.WriteLine(exception.ToString());
            Console.ReadLine();
        }
        Console.WriteLine(response);
        string res = response.ToString();
        Stream ReceiveStream = response.GetResponseStream();

        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

        // Pipe the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader(ReceiveStream, encode);
        Console.WriteLine("\nResponse stream received");
        Char[] read = new Char[256];

        // Read 256 charcters at a time.    
        int count = readStream.Read(read, 0, 256);
        Console.WriteLine("HTML...\r\n");

        while (count > 0)
        {
            // Dump the 256 characters on a string and display the string onto the console.
            String str = new String(read, 0, count);
            Console.Write(str);
            count = readStream.Read(read, 0, 256);
        }

        Console.WriteLine("");
        // Release the resources of stream object.
        readStream.Close();
        Console.ReadLine();

给予:

import struct

val, _ = struct.unpack( '!h', b'23' )
val = (val >> 4) & 0xFFF

但是,您应该检查16个位中有12位被占用了。我之前的代码假定这些是前3个半字节。如果该数字占据较低的3个半字节,则您无需进行任何移位,只需使用>>> hex(val) '0x333' 掩码即可。