cetak the_or(0b1110, 0b101)
Jenis byte di Python tidak dapat diubah dan menyimpan urutan nilai mulai dari 0-255 (8-bit). Anda bisa mendapatkan nilai satu byte dengan menggunakan indeks seperti array, tetapi nilainya tidak dapat diubah
empty_bytes = bytes(4)
print(type(empty_bytes))
print(empty_bytes)_
Tipe Bytearray
Untuk membuat objek yang bisa berubah, Anda perlu menggunakan tipe bytearray. Dengan bytearray Anda dapat melakukan semua yang Anda bisa dengan perubahan lain seperti push, pop, insert, append, delete, dan sort
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)
Kelas BytesIO
Mewarisi dari io. Kelas BufferedReader hadir dengan fungsi seperti read(), write(), peek(), getvalue(). Ini adalah buffer byte umum yang dapat Anda kerjakan
# Binary data and strings are different types, so a str
# must be encoded to binary using ascii, utf-8, or other.
binary_stream.write("Hello, world!\n".encode('ascii'))
binary_stream.write("Hello, world!\n".encode('utf-8'))
# Move cursor back to the beginning of the buffer
binary_stream.seek(0)
# Read all data from the buffer
stream_data = binary_stream.read()
# The stream_data is type 'bytes', immutable
print(type(stream_data))
print(stream_data)
# To modify the actual contents of the existing buffer
# use getbuffer() to get an object you can modify.
# Modifying this object updates the underlying BytesIO buffer
mutable_buffer = binary_stream.getbuffer()
print(type(mutable_buffer)) # class 'memoryview'
mutable_buffer[0] = 0xFF
# Re-read the original stream. Contents will be modified
# because we modified the mutable buffer
binary_stream.seek(0)
print(binary_stream.read())
Menulis Byte ke File
# Pass "wb" to write a new file, or "ab" to appendwith open("test.txt", "wb") as binary_file:
# Write text or bytes to the file
binary_file.write("Write text by encoding\n".encode('utf8'))
num_bytes_written = binary_file.write(b'\xDE\xAD\xBE\xEF')
print("Wrote %d bytes." % num_bytes_written)_
Alternatifnya, Anda dapat secara eksplisit memanggil buka dan tutup, tetapi jika Anda melakukannya dengan cara ini, Anda perlu menangani kesalahan sendiri dan memastikan file selalu ditutup, bahkan jika ada kesalahan saat menulis. Saya tidak merekomendasikan metode ini kecuali Anda memiliki alasan yang kuat
binary_file = open("test.txt", "wb")binary_file.write(b'\x00')
binary_file.close()
Membaca Byte Dari File
with open("test_file.dat", "rb") as binary_file:# Read the whole file at once
data = binary_file.read()
print(data)_
Baca file baris demi baris
Jika Anda mengerjakan file teks, Anda dapat membaca data baris demi baris
# One option is to call readline() explicitly
# single_line = text_file.readline()
# It is easier to use a for loop to iterate each line
for line in text_file:
print(line)
Mendapatkan ukuran file
import osfile_length_in_bytes = os.path.getsize("test.txt")
print(file_length_in_bytes)_
Mencari posisi tertentu dalam file
Anda dapat berpindah ke posisi tertentu dalam file sebelum membaca atau menulis menggunakan seek(). Anda dapat meneruskan satu parameter ke seek() dan itu akan pindah ke posisi itu, relatif terhadap awal file
# Seek can be called one of two ways:# x.seek(offset)
# x.seek(offset, starting_point)
# starting_point can be 0, 1, or 2
# 0 - Default. Offset relative to beginning of file
# 1 - Start from the current position in the file
# 2 - Start from the end of a file (will require a negative offset)
with open("test_file.dat", "rb") as binary_file:
# Seek a specific position in the file and read N bytes
binary_file.seek(0, 0) # Go to beginning of the file
couple_bytes = binary_file.read(2)
print(couple_bytes)_
Integer ke Byte
i = 16# Create one byte from the integer 16
single_byte = i.to_bytes(1, byteorder='big', signed=True)
print(single_byte)
# Create four bytes from the integer
four_bytes = i.to_bytes(4, byteorder='big', signed=True)
print(four_bytes)
# Compare the difference to little endian
print(i.to_bytes(4, byteorder='little', signed=True))
# Create bytes from a list of integers with values from 0-255
bytes_from_list = bytes([255, 254, 253, 252])
print(bytes_from_list)
# Create a byte from a base 2 integer
one_byte = int('11110000', 2)
print(one_byte)
# Print out binary string (e.g. 0b010010)
print(bin(22))
Byte ke Integer
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)0
Pengodean Teks
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)1# Cast bytes to bytearray
mutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)2
Pengkodean Basis 64
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)_3
Heksadesimal
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)_4
Memformat String
String format dapat berguna untuk memvisualisasikan atau menampilkan nilai byte. String format membutuhkan nilai integer sehingga byte harus dikonversi menjadi integer terlebih dahulu
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)5
Operasi Bitwise
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)6
Pengepakan dan Pembongkaran Struktur
Pengemasan dan pembongkaran memerlukan string yang menentukan bagaimana struktur data biner. Perlu mengetahui byte mana yang mewakili nilai. Perlu diketahui apakah seluruh rangkaian byte mewakili karakter atau jika itu adalah urutan bilangan bulat 4-byte. Itu dapat disusun dalam berbagai cara. String format bisa sederhana atau kompleks. Dalam contoh ini saya mengemas satu bilangan bulat empat byte diikuti oleh dua karakter. Huruf i dan c mewakili bilangan bulat dan karakter
# Cast bytes to bytearraymutable_bytes = bytearray(b'\x00\x0F')
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
# Cast bytearray back to bytes
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)7
Urutan Byte Sistem
Anda mungkin perlu mengetahui urutan byte apa yang digunakan sistem Anda. Urutan byte mengacu pada big endian atau little endian. Modul sys dapat memberikan nilai tersebut