# Convert hex string to binary in java

You can use literals like this anywhere that you can use a decimal literal. Shifting and bitwise operations. Java supports a variety of operations to manipulate the bits of an integer: Shift left and right: For shift right, there are two versions: Here are a few examples: One of the primary uses of such operations is shifting and masking , where we isolate a contiguous group of bits from the others in the same word.

Use a shift right instruction to put the bits in the rightmost position. If we want k bits, create a literal mask whose bits are all 0 except its k rightmost bits, which are 1. Use a bitwise and to isolate the bits. The 0s in the mask lead to zeros in the result; the 1s in the mask specify the bits of interest. In the following example, we extract bits 9 through 12 from the bit int. To process text, we need a binary encoding for characters.

The basic method is quite simple: The following table is a definition of ASCII that provides the correspondence that you need to convert from 8-bit binary equivalently, 2-digit hex to a character and back.

For example, 4A encodes the letter J. Unicode is a bit code that supports tens of thousands. The dominant implementation of Unicode is known as UTF UTF-8 is a variable-width character encoding that uses 8 bits for ASCII characters, 16 bits for most characters, and up to 32 bits for other characters. The encoding rules are complicated, but are now implemented in most modern systems such as Java so programmers generally need not worry much about the details.

Big Endian, little endian. Computers differ in the way in which they store multi-byte chunks of information, e. This consists of the two bytes 70 and F2, where each byte encodes 8 bits.

The two are two primary formats, and they differ only in the order or " endianness " in which they store the bytes. Big endian systems store the most significant bytes first, e. Little endian systems store the least significant bytes first, e. This format is more natural when manually performing arithmetic, e.

Intel , Intel Pentium, Intel Xeon use this format. Exercises Convert the decimal number 92 to binary. Convert the hexadecimal number BB23A to octal. Add the two hexadecimal numbers 23AC and 4B80 and give the result in hexadecimal. Assume that m and n are positive integers. What is the only decimal integer whose hexadecimal representation has its digits reversed. Develop an implementation of the toInt method for Converter. Develop an implementation of the toChar method for Converter.

Creative Exercises IP address. Write a program IP. That is, take the bits 8 at a time, convert each group to decimal, and separate each group with a dot. For example, the binary IP address should be converted to Web Exercises Excel column numbering. Write a function elias that takes as input an integer N and returns the Elias Gamma code as a string.

The Elias Gamma code is a scheme to encode the positive integers. To generate the code for an integer N, write the integer N in binary, subtract 1 from the number of bits in the binary encoding, and prepend that many zeros. For example, the code for the first 10 positive integers is given below. Write a function that takes an integer input, reverse its bits, and returns that integer.

Swap elements i and j if i and j are bit reversal of each other. Such permutations arise in the Fast Fourier Transform. What do the following two code fragments do given integers a and b? It works provided a and b are not the same variables in which case both variables are zeroed out.

Find the unique integer. Describe an elegant and efficient algorithm to identify the integer that appears only once.

Bit-whacking version of Gray codes Use bit-whacking operations and iteration instead of recursion to generate a gray code. Name your program BitWhackingGrayCode. Free the prisoners I. A warden meets with 17 new prisoners when they arrive. The warden tells them that they may meet today and plan a strategy, but after the meeting, each prisoner will be in solitary confinement and will not be able to communicate with one another. The prison has a switch room with 17 switches that can be on or off, although the initial configuration is not revealed.

There is one special setting of the 17 switches that if it is ever achieved will enable the prisoners to go free. Each hour the warden escorts one prisoner to the switch room, where the prisoner can flip at most one switch from on to off or off to on. The warden can choose prisoners in arbitrary order, so one prisoner may be chosen four times in a row, or not at all.

Design a strategy for the 17 prisoners so that they are guaranteed to be set free after some finite amount of time. Free the prisoners II. Same premise as above, except that the switch room has 2 switches initially both off , and a prisoner must flip exactly one of the two switches upon entering the switch room. At any time, a prisoner may declare "all 17 of us have visited the control room. The warden can choose prisoners in arbitrary order, so one prisoner may be chosen four times in a row, but each prisoner will be chosen infinitely often assuming they are never freed.

Count the number of 1 bits. Write function that takes an integer input and returns the number of 1's in its binary representation. See if you can figure out how it works. Explain why the following function that often appears in job interviews for programmers correctly counts the number of 1 bits in the binary representation of its input.

If the input has k 1s, how many times does the while loop iterate? Repeat the previous exercise, but pre-compute a table to speed up the computation. You can use the bit counting function from the previous exercise to initialize it. A table of size 2 32 is likely prohibitive. Java library functions for bit-whacking. Re-implement the following static methods that defined in the Integer class. One method that sleazy spammers use to auto-generate email addresses is by enumerating all possible email addresses at a give domain, e.

This annoying tactic is called a dictionary or Rumpelstiltskin attack and explains why you sometimes receive spam on a new email address to which you haven't given to anybody. Breaking a gold chain. You have a gold chain with 14 links that you are going to use to pay an worker for 15 days at a fee of 1 gold link per day.

It's possible to split the chain into 15 pieces by cutting 14 times. Your goal is to pay the worker while only breaking the chain 3 times. The worker must receive exactly the right fraction of total payment after each day of work. Write a Java program HammingEncoder. Write a Java program HammingDecoder.

Modify your solutions to the previous two exercises so that the input bits are packed 8 to the byte. Prove that a k-digit decimal number can be represented in binary with no more than 4k bits. Sum of powers of 2. Compute the sum of powers of 2. What value do you end up with on two's complement machine? CDDB and freedb are databases that allow you to look up CD information on the Web and display the artist, title, and song name.

Each CD has a nearly unique disc ID number which is used to query the database. Write a static method sumDigits that takes an integer parameter and returns the sum of the decimal digits in the integer. Write a program CDDB. The bit 8 hex digit ID number is computed from the length of the tracks on the CD and the number of tracks as follows: Explain why the following code fragment does not leave ABCD in variable a. How would you fix it?

In Java, byte is a signed 8-bit integer. The right-shift promotes b0 to a negative integer. The celebration is the most important party you have ever hosted. You've got bottles of wine you were planning to open for the celebration, but you find out that one of them is poisoned. The actual poison exhibits no symptoms until somewhere around the 23rd hour, then results in sudden death. You have thousands of prisoners at your disposal.

What is the smallest number of prisoners you must have to drink from the bottles to find the poisoned bottle? The sign bit is 0 is the number is positive or zero and 1 if it is negative.

The remaining 10 bits are devoted to the coefficient. The normalization condition implies that the digit before the decimal place in the coefficient is always 1, so we need not include that digit in the representation. The bits are interpreted as a binary fraction, so 1. Encoding and decoding floating-point numbers. Given these rules, the process of decoding a number encoded in IEEE format is straightforward.

The process of encoding a number is more complicated, due to the need to normalize and to extend binary conversion to include fractions. Java uses binary32 for type float 32 bits, with 8 bits for the exponent and 23 bits for the fraction and binary64 for type double 64 bits, with 11 bits for the exponent and 53 bits for the fraction.

This explains the bounds on values of these types and explains various anomolous behavior with roundoff error that we first observed in Section 1. Java code for manipulating bits. Java defines the int data type to be a bit two's complement integer and support various operations to manipulate the bits. Binary and hex literals. You can specify integer literal values in binary by prepending 0b and in hex by prepending 0x.

You can use literals like this anywhere that you can use a decimal literal. Shifting and bitwise operations.

Java supports a variety of operations to manipulate the bits of an integer: Shift left and right: For shift right, there are two versions: Here are a few examples: One of the primary uses of such operations is shifting and masking , where we isolate a contiguous group of bits from the others in the same word.

Use a shift right instruction to put the bits in the rightmost position. If we want k bits, create a literal mask whose bits are all 0 except its k rightmost bits, which are 1. Use a bitwise and to isolate the bits.

The 0s in the mask lead to zeros in the result; the 1s in the mask specify the bits of interest. In the following example, we extract bits 9 through 12 from the bit int. To process text, we need a binary encoding for characters. The basic method is quite simple: The following table is a definition of ASCII that provides the correspondence that you need to convert from 8-bit binary equivalently, 2-digit hex to a character and back.

For example, 4A encodes the letter J. Unicode is a bit code that supports tens of thousands. The dominant implementation of Unicode is known as UTF UTF-8 is a variable-width character encoding that uses 8 bits for ASCII characters, 16 bits for most characters, and up to 32 bits for other characters. The encoding rules are complicated, but are now implemented in most modern systems such as Java so programmers generally need not worry much about the details. Big Endian, little endian.

Computers differ in the way in which they store multi-byte chunks of information, e. This consists of the two bytes 70 and F2, where each byte encodes 8 bits. The two are two primary formats, and they differ only in the order or " endianness " in which they store the bytes.

Big endian systems store the most significant bytes first, e. Little endian systems store the least significant bytes first, e.

This format is more natural when manually performing arithmetic, e. Intel , Intel Pentium, Intel Xeon use this format.

Exercises Convert the decimal number 92 to binary. Convert the hexadecimal number BB23A to octal. Add the two hexadecimal numbers 23AC and 4B80 and give the result in hexadecimal. Assume that m and n are positive integers. What is the only decimal integer whose hexadecimal representation has its digits reversed.

Develop an implementation of the toInt method for Converter. Develop an implementation of the toChar method for Converter. Creative Exercises IP address. Write a program IP. That is, take the bits 8 at a time, convert each group to decimal, and separate each group with a dot. For example, the binary IP address should be converted to Web Exercises Excel column numbering. Write a function elias that takes as input an integer N and returns the Elias Gamma code as a string.

The Elias Gamma code is a scheme to encode the positive integers. To generate the code for an integer N, write the integer N in binary, subtract 1 from the number of bits in the binary encoding, and prepend that many zeros.

For example, the code for the first 10 positive integers is given below. Write a function that takes an integer input, reverse its bits, and returns that integer. Swap elements i and j if i and j are bit reversal of each other. Such permutations arise in the Fast Fourier Transform. What do the following two code fragments do given integers a and b?

It works provided a and b are not the same variables in which case both variables are zeroed out. Find the unique integer. Describe an elegant and efficient algorithm to identify the integer that appears only once. Bit-whacking version of Gray codes Use bit-whacking operations and iteration instead of recursion to generate a gray code. Name your program BitWhackingGrayCode.

Free the prisoners I. A warden meets with 17 new prisoners when they arrive. The warden tells them that they may meet today and plan a strategy, but after the meeting, each prisoner will be in solitary confinement and will not be able to communicate with one another. The prison has a switch room with 17 switches that can be on or off, although the initial configuration is not revealed.

There is one special setting of the 17 switches that if it is ever achieved will enable the prisoners to go free. Each hour the warden escorts one prisoner to the switch room, where the prisoner can flip at most one switch from on to off or off to on. The warden can choose prisoners in arbitrary order, so one prisoner may be chosen four times in a row, or not at all. Design a strategy for the 17 prisoners so that they are guaranteed to be set free after some finite amount of time.

Free the prisoners II. Same premise as above, except that the switch room has 2 switches initially both off , and a prisoner must flip exactly one of the two switches upon entering the switch room. At any time, a prisoner may declare "all 17 of us have visited the control room.

The warden can choose prisoners in arbitrary order, so one prisoner may be chosen four times in a row, but each prisoner will be chosen infinitely often assuming they are never freed. Count the number of 1 bits. Write function that takes an integer input and returns the number of 1's in its binary representation.

See if you can figure out how it works. Explain why the following function that often appears in job interviews for programmers correctly counts the number of 1 bits in the binary representation of its input.

If the input has k 1s, how many times does the while loop iterate? Repeat the previous exercise, but pre-compute a table to speed up the computation. You can use the bit counting function from the previous exercise to initialize it.

A table of size 2 32 is likely prohibitive. Java library functions for bit-whacking. Re-implement the following static methods that defined in the Integer class. One method that sleazy spammers use to auto-generate email addresses is by enumerating all possible email addresses at a give domain, e. This annoying tactic is called a dictionary or Rumpelstiltskin attack and explains why you sometimes receive spam on a new email address to which you haven't given to anybody.

Breaking a gold chain. You have a gold chain with 14 links that you are going to use to pay an worker for 15 days at a fee of 1 gold link per day. It's possible to split the chain into 15 pieces by cutting 14 times. Your goal is to pay the worker while only breaking the chain 3 times. The worker must receive exactly the right fraction of total payment after each day of work. Write a Java program HammingEncoder. Write a Java program HammingDecoder.

Modify your solutions to the previous two exercises so that the input bits are packed 8 to the byte. Prove that a k-digit decimal number can be represented in binary with no more than 4k bits. Sum of powers of 2. Compute the sum of powers of 2. What value do you end up with on two's complement machine? CDDB and freedb are databases that allow you to look up CD information on the Web and display the artist, title, and song name.