簡體   English   中英

從 4 字節十六進制數中讀取經度 [28:0]

[英]Reading the longitude [28:0] from a 4 byte hexadecimal number

我收到一個 4 字節十六進制字符串的經度和准確度: 99054840我正在嘗試從該值中提取經度。

規格告訴我以下內容:

  • 位 [28:0]:有符號值 λ,little-endian 格式,以° 為單位的經度 = λ ÷ 1,000,000

  • 位 [31:29]:無符號值 α,范圍 0-7,精度度量

我的設備實際位於經度 4.7199。 所以我現在轉換的結果應該是什么。

要讀取我當前所做的經度值(結果不正確):

def get_longitude(reading):
    # split in different bytes
    n=2
    all_bytes = [reading[i:i+n] for i in range(0, len(reading), n)]
    
    # convert to binary
    long_bytes_binary = list(map(hex_to_binary, all_bytes))
    
    # drop the accuracy bits
    long_bytes_binary[3] = long_bytes_binary[3][0:5]

    # little endian & concatenate bytes
    longitude_binary = ''.join(list(reversed(long_bytes_binary)))

    # get longitude
    lon = binary_to_decimal(int(longitude_binary))/1_000_000

達到 138.93。 與 4.7199 完全不同(預期結果)

以下是輔助方法

def hex_to_binary(payload):
    scale = 16
    num_of_bits = 8
    binary_payload = bin(int(payload, scale))[2:].zfill(num_of_bits)
    return binary_payload   

def binary_to_decimal(binary): 
  binary1 = binary
  decimal, i, n = 0, 0, 0
  while(binary != 0):
    dec = binary % 10
    decimal = decimal + dec * pow(2, i)
    binary = binary//10
    i += 1
  return decimal 

我究竟做錯了什么? 如何正確讀取值? 還是我的設備壞了:)

為了准確,OP 代碼丟棄了最后 3 位而不是前 3 位。 此更改修復了它:

# drop the accuracy bits
long_bytes_binary[3] = long_bytes_binary[3][3:]

但計算可以簡單得多:

def hex_to_longitude(x):
    b = bytes.fromhex(x)             # convert hex string to bytes
    i = int.from_bytes(b,'little')   # treat bytes as little-endian integer
    return (i & 0x1FFFFFFF) / 1e6    # 29-bitwise AND mask divided by one million

x = '99054840'
print(hex_to_longitude(x))
4.720025

我在這里使用struct進行字節序交換有點作弊,但你明白了。

import struct

val = 0x99054840
val = struct.unpack('<I',struct.pack('>I',val))[0]
print(hex(val))
accuracy = (val >> 29) & 7
longitude = (val & 0x1ffffff) / 1000000
print(accuracy,longitude)

Output:

C:\tmp>x.py
0x40480599
2 4.720025

C:\tmp>                                               ```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM