Converting Decimal to Hexadecimal and Octal

2019-08-02 17:34发布

Show how to write a constant in C, whose decimal value is 65 as

a. a hexadecimal constant
65/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?

3条回答
Emotional °昔
2楼-- · 2019-08-02 17:44

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楼-- · 2019-08-02 17:52

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);
查看更多
祖国的老花朵
4楼-- · 2019-08-02 17:58

You just need a while loop and a string. As this is homework, I do not think I should say more than that.

查看更多
登录 后发表回答