Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary converter #125

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/binary_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
def decimal_to_binary(n):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aggiungi il return value

if n < 0:
raise ValueError("Il numero deve essere positivo")
if n == 0:
return "0"
b = ""
while n > 0:
if n % 2 == 0:
b = "0" + b
else:
b = "1" + b
n //= 2
return b

def main():
n = int(input("Inserisci un numero: "))
binary_number = decimal_to_binary(n)
print("Il numero binario è:", binary_number)

if __name__ == "__main__":
main()

28 changes: 28 additions & 0 deletions tests/test_binary_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pytest
from src.binary_converter import decimal_to_binary

def test_binary_converter():
# Verifica che 1 venga convertito correttamente in "1"
assert decimal_to_binary(1) == '1'

# Verifica che 2 venga convertito correttamente in "10"
assert decimal_to_binary(2) == '10'

# Verifica che 9 venga convertito correttamente in "1001"
assert decimal_to_binary(9) == '1001'

# Verifica che 63 venga convertito correttamente in "111111"
assert decimal_to_binary(63) == '111111'

# Verifica che 256 venga convertito correttamente in "100000000"
assert decimal_to_binary(256) == '100000000'

# Verifica che numeri negativi generino un'eccezione ValueError
with pytest.raises(ValueError):
decimal_to_binary(-5)

# Verifica che 0 venga convertito correttamente in "0"
assert decimal_to_binary(0) == '0'

# Verifica che numeri molto grandi vengano convertiti correttamente
assert decimal_to_binary(1024) == '10000000000'
Loading