만나보세요
새로운 프레젠테이션 도우미가 기다리고 있어요.
뎌욱 빠르게 컨텐츠를 다듬고, 보강하고, 편집하고, 원하는 이미지를 찾고, 시각자료를 편집하세요.
트렌드 검색
In all of these cases, the second value in the bitwise operation is known as the "bit mask".
Because it is an interpreted language, Python code doesn't need to be compiled. Using the interpreter allows you to test code snippets quickly.
Some useful tools in the interpreter:
In Python:
String formatting information: https://docs.python.org/3/library/string.html#format-string-syntax
A technique for selecting subsections of an array-like structure (strings, lists, tuples):
Remember:
[start:stop:skip]
Blocks of code in Python are identified by indentation, not by curly braces.
if True:
print("Python rocks!")
The best practice is to use 4 spaces, not tabs. Either will do, just don't mix them!
Bitwise XOR can be used to toggle specific bit positions:
Bitwise AND can be used to set specific bit positions to 0:
Bitwise OR can be used to set specific bit positions to 1:
Consider starting with a 8-bit long bit string representing 96d and we want to switch all the bit values:
01100000
XOR 11111111
------------------
10011111
An interesting consequence of this is that we can extract the values of bits at certain positions by placing 1's in the bit mask:
11101110
AND 01111000
------------------
01101000
Consider starting with a 8-bit long bit string representing 239d and we want to set the last bit to 0b (make the number 238d):
11101111
AND 11111110
------------------
11101110
So we can use this to combine two bit strings into a single one:
01100000
OR 10000110
----------------
11100110
Consider starting with a 8-bit long bit string representing 96d and we want to set the last bit to 1b (make the number 97d):
01100000
OR 00000001
----------------
01100001
isinstance(X, str)
Is True if X is a string, works with all types and classes, including inherited classes (works like you'd think)
type(a_variable)
Shows the type in the interpreter
Binary:
>>>int('101', 2)
5
>>>"{0:b}".format(13)
'1101'
Hex:
>>> import codecs
>>> codecs.encode(b'hello', 'hex')
b'68656c6c6f'
>>> codecs.decode('776f726c64', 'hex')
'world'
See https://docs.python.org/3/library/codecs.html#standard-encodings
for more encodings
fin = open(name[, mode])
where
name is the file
mode is 'r', 'w', 'a'
binary with 'rb', 'wb', 'ab'
with open("spam.txt") as fin:
# Do stuff
pass
Exception handling and closing the file are automatically done with "with"
Struct objects allow you to "pack" and "unpack" binary data (just like you can with a struct in C) using a format string.
import struct
my_struct = struct.Struct("ii10s")
mydata = my_struct.unpack(byte_data)
Struct objects support many different data types in the format string. For the complete list, see https://docs.python.org/3/library/struct.html#format-strings
A database has a number of fields in the following format:
argparse and optparse: Both are an object-oriented approach to the whole process of specifying and retrieving arguments. This makes them a little complex and hard to remember. Both are part of the Python standard library.
X >> Y
Shift X right by Y bits
X << Y
Shift X left by Y bits
n = 0
with open('file_test2.binary', 'rb') as fin:
bits = 0
while True:
b = fin.read(1)
if not b:
break
n = n | (int.from_bytes(b, "big") << bits)
bits += 8
print(n)
docopt: Follows the POSIX standard for program usage specification, and takes the script's "docstring" as input. Automatically checks that the combination of arguments is correct. Provides a dictionary as output. Has to be installed manually. Used to be my favorite. http://docopt.org
Can you figure out how to do this in only 2 lines of code?
click: Brought to you by the same people that created Flask, the web micro-framework. Uses decorators to route commands to the functions that handle them. Pretty easy to get up and running. Currently my favorite.
https://click.palletsprojects.com/
Feel free to email me at:
mmabey@asu.edu
Two four-byte integers and a 10-character string
if a < b:
print("b is bigger")
elif a > b:
pass # Do nothing
else:
print("same")
Strings and bytes can be encoded and decoded to different types.
Each entry is delimited by \n, which is removed by strip()
fin.close()
Similar to a Hash Table data structure with a key/value pair, plus Python flexibility built-in.
>>> d = {'a': 22, 5: [2, 3, 4], 8.8: {1: 'f'}}
>>> d[5][1]
3
try:
risky_business()
except ValueError as err:
print(err)
except IndexError:
print("Out of bounds!")
else:
# Only done if no error
print("Risk was worth it")
0=beginning
1=current
2=end
The following opens a binary file holding a single number in little-endian, reads one byte at a time, converts it to decimal, and prints it to the screen:
for i in range(12):
print(f"I have {i} pickles") #Python 3.6+
while i > 0:
i -= 1
print("Gave one away,", i, "left")
break and continue work as normal
http://docs.python.org/3/library/operator.html#mapping-operators-to-functions
for line in fin:
print(line)
Converts multiple little-endian bytes into an integer
Navigating binary files is similar to other languages
fin.tell() # Current byte offset
fin.seek(5) # Go to the 5th byte
fin.seek(-3, 2) # Go to the 3rd byte
before the end
fin.read(2) # Read in 2 bytes
Three ways to specify a string:
X & int('1111', 2)
Bitwise AND of X and 15 saves only the last 4 bits of X
X | Y
Bitwise OR of X and Y
X ^ Y
Exclusive OR (XOR) of X and Y
String formatting allows us to specify exactly how each field is printed
Two types of arrays:
a = [1, 'a', 2.0, [3, 4]]
b = (1, 'a', 2.0, [3, 4])
def sum_exponent(a, b, c):
return (a+b)**c