开发者

number conversion general methodology?

This is about how to do number conversion between binary to octal, octal to hexadecimal, binary to hexadecimal.. ( in all these decimal is no where there, either in source or destination )

Whenever decimal is involved either in source or destination i have a general methodology as,

  • if decimal is source, do the mod operation of that number with the base of destination. ( and continue the same way, and get the result ),

    Example: convert decimal 20 to octal

    • 20 mod 8 = 4
      • 2 = 2

So it is 24 in Octal. This way you can do for anything ( binary, hex ) from Decimal.

  • if decimal is destination, do the multiplication operation with the source's base f开发者_JAVA技巧rom 0 to N which starts from left to right. And add up to get the decimal.

    Example: convert binary 1010 to decimal

    • 0 : 0 x 2**0 = 0
      • 1 : 1 x 2**1 = 2
        • 0 : 0 x 2**2 = 0
          • 1: 1 x 2**3 = 8

The sum is 10 in Decimal. This way you can do for anything ( octal, hex ) to decimal.

Questions

Is there any similar general logic, which i can use for conversion between octal, hex and binary ?

Hope the above is clear.. Else let me know.


The conversion between binary and either octal or hex is even easier than decimal. Just break the binary digits up into groups of 3 or 4 (depending on oct or hex), then convert each group to a digit. (If you don't have a multiple of 3 or 4 binary digits, just left-pad the number with zeros.)

Example:

111101111010 binary
1111 0111 1010
   F    7    A
           F7A hex

111101111010
111 101 111 010
  7   5   7   2
           7572 oct

Converting back is just the opposite. Each digit in octal or hex gets converted directly to either 3 or 4 binary digits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜