Skip to content

Instantly share code, notes, and snippets.

@GunjiD
Created July 20, 2020 03:16
Show Gist options
  • Save GunjiD/7ebab93674455a0d1e7b1fcb3bbf7fa8 to your computer and use it in GitHub Desktop.
Save GunjiD/7ebab93674455a0d1e7b1fcb3bbf7fa8 to your computer and use it in GitHub Desktop.
C言語のビットフィールドについて
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netpacket/packet.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#define BUF_SIZ 65536
typedef struct data
{
uint8_t version:4;
uint8_t ihl:4;
} Data;
int main(int argc, char *argv[]){
uint8_t a = 49;
printf("%zu Byte\n", sizeof(struct data));
struct data *ip_h = (struct data*)&a;
printf("%x\n", ip_h->version);
printf("%x\n", ip_h->ihl);
return 0;
}
@GunjiD
Copy link
Author

GunjiD commented Jul 20, 2020

実行結果はこうなる。リトルエンディアンなので 31 -> 13 で表示されるのは正しい

gunzi@LAPTOP-QUV6V5O9:~/bit-field$ ./a.out 
1 Byte
1
3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment