thats stupid that bytes(number) creates a sequence of bytes number long why doesnt it…
- User
thats stupid that bytes(number) creates a sequence of bytes number long why doesnt it convert number to binary?
- Assistant
In Python, the built-in
bytes()constructor isn’t meant to take an integer and “turn it into its binary representation.” Instead:• If you call
bytes(n)with a single integer n, it produces a bytes object of length n, filled with zero bytes.
• If you pass it an iterable of integers, it treats each element as a byte value (0–255).That’s why
>>> bytes(5) b'\x00\x00\x00\x00\x00'is five null bytes, not the bits of the number 5.
How do you actually turn an integer into its binary (bit) form? Here are some options:
-
Get a string of bits
• Using the built-inbin()>>> bin(13) '0b1101'• Or formatted without the
0band with padding:>>> format(13, '08b') # 8-bit, zero-padded '00001101' -
Get a
bytesobject of fixed length
Use the integer methodto_bytes(length, byteorder). For example, to pack a 32-bit unsigned integer:n = 305419896 # example: 0x12345678 b = n.to_bytes(4, 'big') print(b) # b'\x12\x34\x56\x78'— here
'big'means big-endian; use'little'for little-endian. -
Manual bit-tinkering
If you want the raw sequence of 0/1 as bytes:bits = [int(bit) for bit in format(n, 'b')] # bits == [1, 1, 0, 1] for n=13
Putting it all together in your code—e.g. to get each hashed value as a 4-byte little-endian sequence—you’d do:
import numpy as np def print_hex_list(bs): print([b.hex() for b in bs]) primes = np.array([2,3,5,7,11,13,17,19], dtype=float) # 1) fractional part of sqrt fracs = np.sqrt(primes) % 1 # 2) scale to 2^32 and floor vals = np.floor(fracs * 2**32).astype(np.uint32) # 3) convert each to 4-byte little-endian byte_list = [v.to_bytes(4, byteorder='little') for v in vals] print_hex_list(byte_list)This way:
- You get a 4-byte representation of each integer
- You won’t exhaust memory with huge
bytes(n)calls - You can inspect or manipulate the raw binary data exactly as you need!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.