Skip to content

Commit

Permalink
Fix signed_to_unsigned being off by 1
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrookman committed Oct 13, 2020
1 parent 405d7df commit 50d1f67
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions trackrip/pcm.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,23 @@

def signed_to_unsigned(data):
"""
Converts signed data to unsigned data
(that's not exactly what this does but I'm not sure what to call it)
TODO: Figure out exactly why this works.
Converts signed data to unsigned data.
"""
# Python reads bytes as unsigned chars (0 to 255).
# For example: Byte "FF" in a signed file is -1, but Python will read it
# as the unsigned value 255. -1 is halfway in the signed range (-127 to 127)
# at position 127 (counting the sign bit). However, 255 corresponds to the
# very end of the unsigned range. To match the original position as a signed
# number, we subtract 128, landing us at the original position at 127.
# While positive decimals will be the same signed or unsigned (under 127),
# their relative position will change again. 127 is position 255 while
# signed, and 128 while unsigned. We add 128, and arrive at 255, the correct
# position.
converted = bytearray()
for byte in data:
if byte > 127:
signed = byte - 127
signed = byte - 128
else:
signed = byte + 127
signed = byte + 128
converted.append(signed)
return converted

0 comments on commit 50d1f67

Please sign in to comment.