H
This is a naive question:
"%u" % -3
I expect it to print 3. But it still print -3.
Also, if I have an int, I can convert it to unsigned int in C:
int i = -3;
int ui = (unsigned int)i;
Is there a way to do this in Python?
Jack said:This is a naive question:
"%u" % -3
I expect it to print 3. But it still print -3.
Depeneding on how exactly you want it converted:Also, if I have an int, I can convert it to unsigned int in C:
int i = -3;
int ui = (unsigned int)i;
Is there a way to do this in Python?
Internally it uses the C runtime to format the number, but if the number
you ask it to print unsigned is negative it uses %d instead of %u. I have
no idea if it is actually possibly to get a different output for %d versus
%u.
Yes, I guessed that was it.Dan Bishop said:%u used to be different from %d, but it changed because of the int/
long unification in Python 2.4.
Jack said:Also, if I have an int, I can convert it to unsigned int in C:
int i = -3;
int ui = (unsigned int)i;
I just tried it:
main() {
int i = -3;
unsigned int ui = i;
printf("%d\n", ui);
}
prints -3. What do you want the conversion to do? If you want
the absolute value, use abs().
Gabriel Genellina said:Try again with "%u". Passing i or ui makes no difference, both push
the same value on the stack. C relies on the format string to
interpret the arguments.
If you use %u you get a very large positive value, not +3.
Gabriel Genellina said:Exactly, and that's the right value. (unsigned int)(-3) isn't +3.
Paul said:The OP specified that the expected result was 3.
hg said:Dan Bishop wrote:
or abs(-1) ?
The OP specified that the expected result was 3.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.