问题
Show how to write a constant in C, whose decimal value is 65 as
a. a hexadecimal constant65/16 = 1 r1
1/16 = 0 r1
Hexadecimal constant = 11
b. an octal constant (in C)65/8 = 8 r1
8/8 = 1 r0
1/8 = 0 r1
Octal constant = 101
Is this the right way to convert constants in C?
回答1:
You just need a while loop and a string. As this is homework, I do not think I should say more than that.
回答2:
The method is to divide by the base until the result is less than the base.
So 65/8 gives 8 r1 but you don't stop there because the result is 8 not less than 8
You divide by 8 again and get 1
It should be
65/64 = 10 r 1 where 64 = 8x8 = octal 10
I don't think I've said too much
回答3:
Maybe I am misunderstanding the questions, but it seems like you are being asked how hex and oct constants are represented in C, not how to implement an algorithm to convert dec to hex and oct.
If that is the case:
hex numbers are represented by a preceding 0x or 0X
oct numbers are represented by a preceding 0
int hex = 0x41;
int oct = 0101;
Of course, you can verify this by printing our the values in decimal:
printf("%d\n", hex);
printf("%d\n", oct);
来源:https://stackoverflow.com/questions/5932235/converting-decimal-to-hexadecimal-and-octal