LoginSignup
1
1

More than 1 year has passed since last update.

Pythonでビット操作してみる

Last updated at Posted at 2021-11-26

スクリプト

#!/usr/bin/env python3

import sys


def format_bit_image(value):
  bit_str = format(value, "b").zfill(32)
  return " ".join([bit_str[0:8], bit_str[8:16], bit_str[16:24], bit_str[24:32]])


def get_4octets(str):
  int_list = [int(x) for x in str.split(".")]  # using list comprehension
  return int_list[0] << 24 | int_list[1] << 16 | int_list[2] << 8 | int_list[3]


def get_str_expression(value):
  p = []
  p.append(value >> 24 & 0xFF)
  p.append(value >> 16 & 0xFF)
  p.append(value >> 8 & 0xFF)
  p.append(value & 0xFF)
  str_p = [str(x) for x in p]

  return ".".join(str_p)


def show_info(label, value):
  print(
      "%-14s = %d {%s} %s [%s]"
      % (label, value, format_bit_image(value), hex(value), get_str_expression(value))
  )


if len(sys.argv) != 3:
  print("Usage: %s [IP address] [Netmask]" % sys.argv[0])
  exit(1)

ip_addr = get_4octets(sys.argv[1])
netmask = get_4octets(sys.argv[2])
show_info("ip_addr", ip_addr)
show_info("netmask", netmask)
network_addr = ip_addr & netmask
show_info("network_addr", network_addr)
broadcast_addr = ip_addr | (~netmask & 0xFFFFFFFF)
show_info("broadcast_addr", broadcast_addr)

実行結果

% printf "%d\n" 0xf0         
240
% ./network_address.py 192.168.125.130 255.255.255.240
ip_addr        = 3232267650 {11000000 10101000 01111101 10000010} 0xc0a87d82 [192.168.125.130]
netmask        = 4294967280 {11111111 11111111 11111111 11110000} 0xfffffff0 [255.255.255.240]
network_addr   = 3232267648 {11000000 10101000 01111101 10000000} 0xc0a87d80 [192.168.125.128]
broadcast_addr = 3232267663 {11000000 10101000 01111101 10001111} 0xc0a87d8f [192.168.125.143]
% 
1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1