Reputation: 571
I have the following code in C
#include <stdio.h>
int main ()
{
unsigned char mask = 0xAB;
for (int i = 0; i < 20; i++)
{
printf ("%d - %x\n", mask, mask);
mask += 9;
}
return 0;
}
Output in C
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
5 - 5
14 - e
23 - 17
32 - 20
41 - 29
50 - 32
59 - 3b
68 - 44
77 - 4d
86 - 56
Now in Python:
mask = 0xab
for i in range(20):
print("{0:d} - {0:x}".format(mask,mask))
mask = (mask + 9) % 0xFF
OutPut Python:
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
6 - 6
15 - f
24 - 18
33 - 21
42 - 2a
51 - 33
60 - 3c
69 - 45
78 - 4e
87 - 57
As you can see, the correct output is that of the C code, but in python I have tried in various ways using pack(), to_bytes() but I can't find the correct result, how can I correct it?
Thanks in advance
Upvotes: 1
Views: 685
Reputation: 24907
You should modulo with 256(Hex: 0x100
). This is because C unsigned char
data type ranges from 0
to 255
.
>>> mask = 0xab >>> for i in range(20): ... print("{0:d} - {0:x}".format(mask,mask)) ... mask = (mask + 9) % 0x100 ...
This will produce the same output as like your C code!.
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
5 - 5
14 - e
23 - 17
32 - 20
41 - 29
50 - 32
59 - 3b
68 - 44
77 - 4d
86 - 56
Upvotes: 1