(Sponsor) Mulailah belajar Python dengan tutorial Intro to Python gratis dari DataCamp. Pelajari Ilmu Data dengan menyelesaikan tantangan coding interaktif dan menonton video dari instruktur ahli. Mulai sekarang Show
Diperbarui pada 07 Januari 2020 Fungsi 1 2 3 4 5 6 7 8 9 10 11 123 menampilkan representasi biner dari bilangan bulat sebagai string Sintaksnya adalah sebagai berikut bin(number) -> binary representation_ ParameterDescription 1 2 3 4 5 6 7 8 9 10 11 124Any numeric value Ini sebuah contoh 1 2 3 4 5 6 7 8 9 10 11 12 >>> >>> bin(4) # convert decimal to binary '0b100' >>> >>> >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255 '0b11111111' >>> >>> >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20 '0b10100' >>>_
bin() dengan objek yang ditentukan penggunaUntuk menggunakan 1 2 3 4 5 6 7 8 9 10 11 123 dengan objek yang ditentukan pengguna, pertama-tama kita harus membebani metode 1 2 3 4 5 6 7 8 9 10 11 126 . Metode 1 2 3 4 5 6 7 8 9 10 11 126 digunakan untuk memaksa objek menjadi bilangan bulat, dalam konteks pemotongan dan pengindeksan. Sebagai contoh, pertimbangkan hal berikut 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17_ >>> >>> l = [1, 2, 3, 4, 5] >>> >>> x, y = 1, 3 >>> >>> >>> l[x] 2 >>> >>> >>> l[y] 4 >>> >>> >>> l[x:y] [2, 3] >>>
Saat kami mengakses item dalam daftar menggunakan pengindeksan dan pemotongan, secara internal Python memanggil metode 1 2 3 4 5 6 7 8 9 10 11 126 dari objek 1 2 3 4 5 6 7 8 9 10 11 129 1 2 3 4 5 6 7 8 9 10 11 12 >>> >>> l[x.__index__()] # same as l[x] 2 >>> >>> >>> l[y.__index__()] # same as l[y] 4 >>> >>> >>> l[x.__index__():y.__index__()] # # same as l[x:y] [2, 3] >>>
Selain 1 2 3 4 5 6 7 8 9 10 11 123, metode 1 2 3 4 5 6 7 8 9 10 11 126 juga dipanggil saat Anda memanggil >>> >>> bin(4) # convert decimal to binary '0b100' >>> >>> >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255 '0b11111111' >>> >>> >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20 '0b10100' >>>2, dan >>> >>> bin(4) # convert decimal to binary '0b100' >>> >>> >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255 '0b11111111' >>> >>> >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20 '0b10100' >>>3 pada objek. Ini sebuah contoh 1 2 3 4 5 6 7 8 9 10 11 120 1 2 3 4 5 6 7 8 9 10 11 12_1 1 2 3 4 5 6 7 8 9 10 11 12_2 Tutorial Lainnya (Sponsor) Situs ini dengan murah hati didukung oleh DataCamp. DataCamp menawarkan Tutorial Python interaktif online untuk Ilmu Data. Bergabunglah dengan lebih dari satu juta pelajar lainnya dan mulai belajar Python untuk ilmu data hari ini Metode Python bin() mengonversi nilai integer menjadi representasi string dari representasi binernya. Metode bin() Python juga dapat digunakan untuk mengembalikan representasi biner dari objek apa pun yang telah menerapkan metode __index__ yang valid Daftar isi Fungsi bawaan Python # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 adalah alat yang berguna dalam menerjemahkan antara bahasa, domain, dan memahami dasar-dasar bagaimana data tingkat rendah direpresentasikan. Pada artikel ini, Anda akan mempelajari penggunaan dasar fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3, beberapa penggunaan tingkat lanjut, dan cara-cara di mana seseorang dapat merusak sesuatu dengan menggunakannya TL;DR – Fungsi Python # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 mengembalikan representasi string dari nilai biner bilangan bulat # Define a number >>> number = 42 42 # Use bin to get binary value >>> bin(number) 0b101010 # Check the type >>> type(bin(number)) <class 'str'> # Only works for integers >>> bin(42.0) TypeError: 'float' object cannot be interpreted as an integer Penggunaan DasarFungsi Python # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 dapat digunakan untuk berbagai aplikasi di mana nilai biner menarik. Kasus penggunaan paling sederhana adalah mengembalikan nilai biner dari nilai bilangan bulat—satu-satunya representasi numerik yang valid yang akan diterima oleh fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3. Mari kita lihat itu beraksi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'> Beberapa hal yang perlu diperhatikan di sini
Fungsi Python bin() akan menunjukkan kepada Anda representasi biner dari sebuah angka, tetapi tidak banyak yang dapat Anda lakukan dengan informasi tersebut secara eksplisit. Sebagai contoh, mari kita coba mengonversi string biner menjadi nilai heksadesimal # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer Astaga. Jadi itu bukan berita bagus tetapi perilaku yang diharapkan mengingat penerapan fungsi hex(). Pertimbangkan bagaimana menjelaskan penggunaannya Mengonversi bilangan bulat menjadi string heksadesimal huruf kecil yang diawali dengan "0x". Jika tujuan kita yang sebenarnya adalah mendapatkan nilai heksadesimal 42, ini akan menjadi contoh konyol—kita akan melewatkan fungsi # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer1) secara bersamaan. # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer_2. Tapi kami sedang belajar di sini, jadi mari kita abaikan cegukan itu dan lihat beberapa contoh yang lebih konyol Lihat artikel tentang cara mengonversi nilai heksadesimal ke biner dengan Python untuk contoh lebih lanjut tentang bagaimana fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 dan # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer4 bekerja bersama (juga bagaimana terkadang mereka merusak sesuatu. ) Menggunakan Bin pada Objek Non-Bilangan BulatIngatlah bahwa Python mewakili semua data sebagai objek. Ini penting untuk memahami bagaimana fungsi Python ________24______3 akan berinteraksi dengan objek lain. Beberapa fitur bahasa seperti operator dan kondisional adalah kasus khusus tetapi, untuk yang lainnya, Python memodelkannya sebagai objek dengan banyak atribut dan metode yang tersedia. Misalnya, mari kita periksa di balik layar nilai sederhana kita 42 menggunakan metode # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer6 # Get a list of valid attributes for our int 'object' >>> dir(42) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] Wow. Ada banyak hal yang terjadi di sini. Jangan khawatir saya tidak akan mencoba dan membongkar semua itu. Baru tahu; Untuk saat ini, satu-satunya atribut yang akan kita fokuskan adalah atribut # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer7. Fitur bahasa ini tersedia melalui PEP357 sekitar Python versi 2. 5 (awal 2006) dan dijelaskan sebagai berikut PEP ini mengusulkan penambahan … metode khusus __index__ sehingga objek arbitrer dapat digunakan kapan pun bilangan bulat diperlukan secara eksplisit di Python … Dengan kata lain, kita dapat membuat objek khusus berfungsi dengan fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 dengan menerapkan metode # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer7 khusus. Pertimbangkan yang berikut ini class CustomHex: """A custom hexadecimal representation of an integer""" def __init__(self, num: int): self.value = hex(num) # Define an integer value num = 42 # Show as built-in hex print(hex(42)) >>> 0x2a # Create custom hex object better_hex = CustomHex(num) # See hex value print(better_hex.value) >>> 0x2a # Get binary value print(bin(better_hex)) >>> TypeError: 'CustomHex' object cannot be interpreted as an integer Di sini saya telah membuat kelas # Get a list of valid attributes for our int 'object' >>> dir(42) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']0 khusus yang mengonversi nilai bilangan bulat dan menyimpannya secara internal sebagai string heksadesimal yang direferensikan oleh atribut # Get a list of valid attributes for our int 'object' >>> dir(42) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']1 objek. Saat objek ini diteruskan ke metode # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>_3, ini menghasilkan # Get a list of valid attributes for our int 'object' >>> dir(42) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']3 Kesalahan ini terjadi karena objek kita tidak memberi tahu Python bagaimana seharusnya direpresentasikan sebagai bilangan bulat. Mari kita lihat apa yang terjadi saat kita menerapkan metode # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer7 khusus seperti yang disarankan oleh dokumentasi class CustomHex: """A custom hexadecimal representation of an integer""" def __init__(self, num: int): self.value = hex(num) def __index__(self): """Custom method to define the integer representation""" return int(self.value, 16) # Instantiate a new CustomHex object better_hex = CustomHex(42) # Get binary value print(bin(better_hex)) >>> 0b101010 Itu bingo. Contoh ini mengilustrasikan, meskipun dalam imajinasi buatan lainnya, bagaimana fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 dapat digabungkan dengan atribut # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer7 untuk mewakili apa saja sebagai string biner di Python. Apakah ini kasus yang umum? Kasus UmumFungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 Python melayani tujuannya dengan baik. Ada sejumlah penggunaan kasus umum di mana metode ini digunakan. Apakah Anda ingin mengubah int menjadi string biner, string menjadi biner, atau string biner menjadi int—fungsi bawaan Python # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 dapat membantu. Dalam beberapa kasus, mungkin memerlukan penggunaan built-in lain seperti fungsi # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer4 untuk menerjemahkan antar nilai. Ayo ambil # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>_3 untuk berputar() Mengkonversi Int ke BinerBilangan bulat adalah kasus penggunaan klasik untuk fungsi bin() Python. Mereka dapat digunakan secara langsung untuk mengekstrak representasi biner seperti itu # Get the binary value of an integer >>> bin(42) 0b101010 Ini mengembalikan objek # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>8 menggunakan sesedikit mungkin 1 dan 0. Perhatikan awalan 0b. Tidak ada cara built-in untuk menghapus notasi itu tetapi, dengan menggunakan pengindeksan string, itu bisa dilakukan dengan cukup mudah >>> bin(42)[2:] 101010 Cukup mudah. Mari pertimbangkan bagaimana seseorang dapat mengembalikan representasi biner dari sebuah string String ke BinerPerlu diingat bahwa segala sesuatu dalam komputasi non-kuantum bermuara pada 1 dan 0. String tidak terkecuali. Jumlah 1 dan 0 yang diperlukan untuk merepresentasikan teks dengan cepat menjadi tidak praktis tetapi masih dapat dilihat dengan cukup mudah menggunakan fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 Python. Untuk ini, kita harus menggunakan fungsi ord() Python untuk mendapatkan nilai integer dari setiap karakter dalam sebuah string >>> "-".join(bin(ord(c))[2:] for c in 'overcoded') 1101111-1110110-1100101-1110010-1100011-1101111-1100100-1100101-1100100 (Uh oh, satu kalimat. ) Di sini saya telah membuat string biner untuk kata class CustomHex: """A custom hexadecimal representation of an integer""" def __init__(self, num: int): self.value = hex(num) # Define an integer value num = 42 # Show as built-in hex print(hex(42)) >>> 0x2a # Create custom hex object better_hex = CustomHex(num) # See hex value print(better_hex.value) >>> 0x2a # Get binary value print(bin(better_hex)) >>> TypeError: 'CustomHex' object cannot be interpreted as an integer3 dengan nilai biner masing-masing karakter yang dipisahkan oleh tanda hubung tunggal untuk kejelasan visual dan menghilangkan class CustomHex: """A custom hexadecimal representation of an integer""" def __init__(self, num: int): self.value = hex(num) # Define an integer value num = 42 # Show as built-in hex print(hex(42)) >>> 0x2a # Create custom hex object better_hex = CustomHex(num) # See hex value print(better_hex.value) >>> 0x2a # Get binary value print(bin(better_hex)) >>> TypeError: 'CustomHex' object cannot be interpreted as an integer4 terdepan juga. Hoop-jumping menggunakan fungsi ord(), sekali lagi, untuk memenuhi kebutuhan fungsi bin() Python untuk nilai integer Biner ke IntFungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>_3 Python menuntut nilai bilangan bulat tetapi dapatkah nilai biner dengan mudah diubah menjadi bilangan bulat? val = bin(42) print(val, type(val)) >>> 0b101010 <class 'str'> int(val) >>> ValueError: invalid literal for int() with base 10: '0b101010' Tampaknya fungsi # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>_3 Python adalah fungsi yang cukup sederhana tetapi, seperti banyak fungsi sederhana lainnya, ada lebih banyak cerita. Kasus memberi makan # Define a number number = 42 # Get its binary value via bin() bin_value = bin(42) # Display the value, check the type print(bin_value) print(type(bin_value)) # Output 0b101010 <class 'str'>3 angka perwakilan yang keliru (misalnya nilai bilangan bulat yang tidak dikonversi) atau objek tanpa # Convert to hexadecimal hex_value = hex(bin_value) # Result TypeError: 'str' object cannot be interpreted as an integer7 atribut yang diterapkan dapat mendatangkan malapetaka dan mengakibatkan class CustomHex: """A custom hexadecimal representation of an integer""" def __init__(self, num: int): self.value = hex(num) def __index__(self): """Custom method to define the integer representation""" return int(self.value, 16) # Instantiate a new CustomHex object better_hex = CustomHex(42) # Get binary value print(bin(better_hex)) >>> 0b1010109 yang tidak selalu jelas Apa fungsi dari bin?Metode bin() mengonversi bilangan bulat tertentu ke representasi binernya dan mengembalikannya .
Bagaimana Anda mendefinisikan bin dengan Python?Python bin() mengembalikan string biner dari bilangan bulat yang diberikan. . Sintaksis. bin(a) Parameter. sebuah. bilangan bulat untuk dikonversi Nilai Pengembalian. String biner dari objek integer atau int Pengecualian. Menaikkan TypeError saat nilai float dikirim dalam argumen Bagaimana cara membuat tempat sampah dengan Python?Fungsi Python berikut dapat digunakan untuk membuat tempat sampah. . def create_bins(batas_bawah, lebar, kuantitas). """ create_bins mengembalikan partisi dengan lebar (jarak) yang sama. . tempat sampah = buat_tempat sampah(batas_bawah=10, lebar=10, jumlah=5) tempat sampah Bagaimana Anda menulis fungsi biner dengan Python?Dengan Python, Anda cukup menggunakan fungsi bin() untuk mengonversi dari nilai desimal ke nilai biner yang sesuai . Demikian pula, fungsi int() untuk mengonversi biner menjadi nilai desimalnya. Fungsi int() mengambil sebagai argumen kedua basis angka yang akan dikonversi, yaitu 2 dalam kasus bilangan biner. |