Reputation: 1
I am writing a Caesar cipher program and i need to keep my values within the range of 32 and 126 ( the printable ascii set) when it encrypts itself. so when it gets to 126 it loops back to 32
here is the code
print("enter sentence to encrypt:")
string = input()
print("Please enter positive offset value:")
value = int(input())
finalstring = [ord(c) for c in string]
finalstring[:] = [c + value for c in finalstring]
finalstring = ''.join(chr(i) for i in finalstring)
Upvotes: 0
Views: 1423
Reputation: 882226
Assuming you have a variable v
that you wish to add a
to, and have it constrained to the range 32..126
inclusive, this should do:
v = (v - 32 + a) % (127 - 32) + 32
So, for example, when adding 3 to 125:
v = (125 - 32 + 3) % (127 - 32) + 32
= 96 % 95 + 32
= 1 + 32
= 33
More generally:
def addWithConstraint (loval, hival, val, plus):
return (val - loval + plus) % (hival + 1 - loval) + loval
Do note however that some modulo operations may not do what you expect for negative numbers but you can get around that by ensuring that you're always adding a positive numbers. For example, you could insert at the start of that function something like:
while plus < 0:
plus = plus + hival + 1 - loval
Upvotes: 3