# Convert decimal to binary java example

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? Describe how to simulate bit unsigned integers in Java. First, are you sure that you really need an unsigned type. Comparison operators are easy to simulate by checking the sign bit.

Division and remainder are the trickiest: Describe how to simulate 8-bit unsigned integers in Java. Same advice as previous question. One place where it's nice to have unsigned integers is for a lookup table, indexed by the byte. With signed integers the index can be negative. Also, if b is a byte , then b automatically casts b to an int. This could be undesirable since b is signed. In many applications you need to remove the signed extended bits via b.

Adding two short integers. Explain why the following code fragment fails. Java automatically promotes the results of most integer operations to be of type int. Yes, this is rather quirky. Explain why b give weird results when b is of type byte. In Java, byte is an 8-bit signed integer. Before the right shift, b is converted to an integer. What does the following code fragment from program Overflow. Suppose a is a variable of type int.

What does the following code fragment print out? What does the following code do to the integers stored in two different variables a and b? Any problems with overflow? What is the value of cnt after the following loop? Explain why the following Java code fragment correctly determines whether the integer n is a power of 2.

Use the definition of the positional notation to define the base -2 number system. There are two digits 0 and 1. Count from -7 to 7 in this system. The format consists of four integers, representing the red, green, and blue intensities from 0 not present to fully used , and also the alpha transparency value from 0 transparent to opaque.

The four 8-bit integers are compacted into a single bit integer. Write a code fragment to extract the four components from the RGBA integer, and to go the other way. One of the following computes min a, b , the other computes max a, b without branching. Explain how it works. Suppose you have an array consisting of 2 32 - 1 integers of type int such that no two integer appears more than once. Since there are 2 32 possible values, exactly one integer is missing. Write a code fragment to find the missing integer using as little extra storage as possible.

It's possible to do it using only one extra int. Use either properties of integer overflow on two's complement integers or use the XOR function. Last modified on July 25, Writing Clear Code C.

Matlab Programming Assignments 6. Zero out all but the leftmost one bit of x. Zero out all but the rightmost one bit of x. Number of zero bits preceding highest one bit. Number of zero bits following lowest one bit. Rotate of x by circularly shifting i bits to the left.

The same procedure generalizes to any base by replacing 10 with the desired base. We can represent only 2 n integers in an n -bit word. For example, with bit words, we can represent the integers from 0 to 65, Wee need to pay attention to ensure that the value of the result of an arithmetic operation does not exceed the maximum possible value.

This condition is called overflow. For addition of unsigned integers, overflow is easy to detect: The grade-school algorithm for multiplication works perfectly well with any base. Detecting overflow is a bit more complicated than for unsigned integers.

To negate a two's complement integer, flip the bits and then add 1. This explains the bounds on values of these types and explains the behavior on overflow in Java that we first observed in Section 1.

The IEEE standard defines the behavior of floating-point number of most computer systems. For simplicity, we illustrate with a bit version known as half-precision binary floating point or binary16 for short. The same essential ideas apply to the bit and bit versions used in Java, which we refer to as binary32 and binary The real-number representation that is commonly used in computer systems is known as floating point.

It is just like scientific notation, except that everything is represented in binary. Just as in scientific notation, a floating-point number consists of a sign , a coefficient , and an exponent.

The first bit of a floating-point number is its sign. 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.