# G.2 Relationship between Binary, Octal, and Hexadecimal Numbers

From Table G.1 we see that 3 bits are needed to represent any octal digit, and 4 bits to are needed to represent any hexadecimal digit. We can use this fact to convert between binary, octal, and hexadecimal systems, as shown in Figure G.1.

##### Figure G.1. Converting between Binary, Octal, and Hexadecimal The procedure for converting an octal to a binary is shown by the arrow marked (a). We can prove that replacing each octal digit by its 3-bit equivalent binary value gives the right result:

 1738 = 1x82 + 7x81 + 3x80 = 1x(23)2 + 7x(23)1 + 3x(23)0 = 1x26 + 7x23 + 3 = (0012)x26 + (1112)x23 + (0112) = (0x22+0x21+1x20)x26 + (1x22+1x21+1x20)x23 + (0x22+1x21+1x20) = 1x26 + 1x25+1x24+1x23 + 0x22+1x21+1x20 = 1x26 + 1x25 + 1x24 + 1x23 + 0x22 + 1x21 + 1x20 = 11110112

Analogously, we can convert a hexadecimal number to its equivalent binary number by replacing each digit in the hexadecimal number by its 4-bit equivalent binary value, as shown by the arrow marked (b).

To convert a binary to it octal equivalent, we reverse the procedure outlined earlier (see arrow marked (c) in Figure G.1). The bits in the binary number are grouped into 3-bit groups from right to left. Each such group is replaced by its equivalent octal digit. This corresponds to reversing the computation shown above. Analogously, we can convert a binary to a hexadecimal number by replacing each 4-bit group by its equivalent hex digit (see arrow marked (d) in Figure G.1).   List of Figures  List of Tables  List of Examples  Foreword  Preface  Chapter 1. Basics of Java Programming  Chapter 2. Language Fundamentals  Chapter 3. Operators and Assignments  Chapter 4. Declarations and Access Control  Chapter 5. Control Flow, Exception Handling, and Assertions  Chapter 6. Object-oriented Programming  Chapter 7. Nested Classes And Interfaces  Chapter 8. Object Lifetime  Chapter 9. Threads  Chapter 10. Fundamental Classes  Chapter 11. Collections and Maps  Appendix A. Taking the SCPJ2 1.4 Exam  Appendix B. Objectives for the SCPJ2 1.4 Exam  Appendix C. Objectives for the Java 2 Platform Upgrade Exam  Appendix D. Annotated Answers to Review Questions  Appendix E. Solutions to Programming Exercises  Appendix F. Mock Exam  Appendix G. Number Systems and Number Representation  G.1 Number Systems  G.2 Relationship between Binary, Octal, and Hexadecimal Numbers  G.3 Converting Decimals  G.4 Representing Integers  Appendix H. About the CD  Single-User License Agreement