![](/img/trans.png)
[英]Using bit fields in struct and reading an instance from Memory with C++
[英]reading fields from bit array/bitmap in c++
背景:
我有興趣使用定義一組字段的位數組/位圖。 具體來說,我想解析radiotap標題但我有一些概念問題(或者,更可能的是,我只是錯過了一些關於這一切是如何工作的)。
位數組描述的字段,即radiotap標頭,在上面的鏈接中定義。
問題:(編輯)
例如,當我的數據是u_char流時,我將如何讀取位圖和字段中的值? 如果我知道它的存在是由位圖指示的,我如何訪問一個字段?
我認為這里的解決方案將與位移/屏蔽有關,但這是我第一次嘗試低級別的編程,我不知道如何開始解決這個問題。
編輯:
目前我的問題是我正在從u_char指針讀取802.11幀,但是我一直在以編程方式從這里開始訪問我知道的頭部和字段,首先是radiotap頭。
//defined by library I'm using
struct packet_header {
struct timeval ts; /*timestamp*/
bpf_u_int32 caplen; /*number of stored bytes*/
bpf_u_int32 length; /*total length of packet*/
}
struct packet_header hdr; //see above, basic info
u_char *packet //the data
for(int i = 0; i < hdr->length; i++){
//parse/analyse data contained in the frame/packet (1st radiotap)
packet[i] //do something with u_char here, but what exactly?
}
我建議你仔細研究這個頁面: http : //www.radiotap.org/Radiotap
標題的it_present
字段指示標題it_present
字段。 並且存在的字段按其位數順序排列,從最低到最高。 因此,例如,如果it_present
的第一個非零位是位3,則標題之后的第一個字段將是通道。
該協議非常復雜,必須遵循許多規則。 例如,如果設置了it_present
31位,則代替緊跟在標題之后的字段,首先存在更多的存在位。 您還必須了解字段的對齊方式。 字段之間可能存在填充,因此32位字段在4字節邊界上對齊,64位字段在8字節邊界上對齊,依此類推。
編輯:假設packet
指向radiotap頭的開頭,而pkt_len
是字節數。 你可以像這樣開始:
pkt_len = hdr.length;
if ( pkt_len >= sizeof(ieee80211_radiotap_header) )
{
u_int16_t it_len;
u_int32_t it_present;
u_int32_t tmpMask;
u_int32_t* pExtraMask;
u_int32_t* pNextMask;
u_int32_t uMask;
int iFldNum;
ieee80211_radiotap_header* pPktHdr = (ieee80211_radiotap_header*) packet;
pkt_len -= sizeof(ieee80211_radiotap_header);
packet += sizeof(ieee80211_radiotap_header);
it_len = le16_to_cpu(pPktHdr->it_len); // Get radiotap packet length from header
it_present = le32_to_cpu(pPktHdr->it_present); // Get present field bitmask
// Find end of radiotap header
tmpMask = it_present;
pExtraMask = pNextMask = (u_int32_t*) packet;
while ( (tmpMask & 0x80000000) && (pkt_len >= sizeof(u_int32_t)) )
{
tmpMask = le32_to_cpu(*pNextMask++);
pkt_len -= sizeof(u_int32_t);
packet += sizeof(u_int32_t);
}
// packet should now point to the first field
for ( iFldNum = 0, uMask = 1; (iFldNum < 31) && pkt_len; ++iFldNum, uMask <<= 1 )
{
if ( (it_present & uMask) )
{
u_int16_t uFldLen;
// We have a non-zero bit in the mask, iFldNum is the field number
// Call function to extract the field at packet and return number of bytes used
// process_field() is responsible for data alignment and preventing buffer overrun
uFldLen = process_field(packet, pkt_len, iFldNum);
pkt_len -= uFldLen;
packet += uFldLen;
}
}
// Here you would check if it_present had bit 31 set
// If so, process additional masks starting at pExtraMask
}
如你所見,它可能有點毛茸茸。
我不確定我的問題是否正確。 我假設你問的是如何在第3位讀取一些值。
因此,您可以正常讀取值並將其左移3個位置。
x = 1; x = x << 3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.