Algorithm to convert a String of decimal digits to BCD - java

I am looking a way to convert a string to BCD equivalent. I use Java, but it is not a question of the language indeed. I am trying to understand step by step how to convert a string to BCD.
For example, suppose I have the following string;
"0200" (This string has four ASCII characters, if we were in java this string had been contained in a byte[4] where byte[0] = 48, byte[1] = 50, byte[2] = 48 and byte[3] = 48)
In BCD (according this page: http://es.wikipedia.org/wiki/Decimal_codificado_en_binario):
0 = 0000
2 = 0010
0 = 0000
0 = 0000
Ok, I think the conversion is correct but I have to save this in a byte[2]. What Should I have to do? After, I have to read the BCD and convert it to the original string "0200" but first I have to resolve String to BCD.

Find a utility class to do this for you. Surely someone out there has written a BCD conversion utility for Java.
Here you go. I Googled "BCD Java" and got this as the first result. Copying code here for future reference.
public class BCD {
/*
* long number to bcd byte array e.g. 123 --> (0000) 0001 0010 0011
* e.g. 12 ---> 0001 0010
*/
public static byte[] DecToBCDArray(long num) {
int digits = 0;
long temp = num;
while (temp != 0) {
digits++;
temp /= 10;
}
int byteLen = digits % 2 == 0 ? digits / 2 : (digits + 1) / 2;
boolean isOdd = digits % 2 != 0;
byte bcd[] = new byte[byteLen];
for (int i = 0; i < digits; i++) {
byte tmp = (byte) (num % 10);
if (i == digits - 1 && isOdd)
bcd[i / 2] = tmp;
else if (i % 2 == 0)
bcd[i / 2] = tmp;
else {
byte foo = (byte) (tmp << 4);
bcd[i / 2] |= foo;
}
num /= 10;
}
for (int i = 0; i < byteLen / 2; i++) {
byte tmp = bcd[i];
bcd[i] = bcd[byteLen - i - 1];
bcd[byteLen - i - 1] = tmp;
}
return bcd;
}
public static String BCDtoString(byte bcd) {
StringBuffer sb = new StringBuffer();
byte high = (byte) (bcd & 0xf0);
high >>>= (byte) 4;
high = (byte) (high & 0x0f);
byte low = (byte) (bcd & 0x0f);
sb.append(high);
sb.append(low);
return sb.toString();
}
public static String BCDtoString(byte[] bcd) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bcd.length; i++) {
sb.append(BCDtoString(bcd[i]));
}
return sb.toString();
}
}
There's also this question: Java code or lib to decode a binary-coded decimal (BCD) from a String.

The first step would be to parse the string into an int so that you have the numeric value of it. Then, get the individual digits using division and modulus, and pack each pair of digits into a byte using shift and add (or shift and or).
Alternatively, you could parse each character of the string into an int individually, and avoid using division and modulus to get the numbers, but I would prefer to parse the entire string up front so that you discover right away if the string is invalid. (If you get a NumberFormatException, or if the value is less than 0 or greater than 9999 then it is invalid.)
Finally, once you have assembled the two individual bytes, you can put them into the byte[2].

You can use following:
//Convert BCD String to byte array
public static byte[] String2Bcd(java.lang.String bcdString) {
byte[] binBcd = new byte[bcdString.length() / 2];
for (int i = 0; i < binBcd.length; i++) {
String sByte = bcdString.substring(i*2, i*2+2);
binBcd[i] = Byte.parseByte(sByte, 16);
}
return binBcd;
}

You can try the following code:
public static byte[] hex2Bytes(String str) {
byte[] b = new byte[str.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = str.charAt(j++);
char c1 = str.charAt(j++);
b[i] = ((byte) (parse(c0) << 4 | parse(c1)));
}
return b;
}

Related

Java. Extracting integers from bits in a byte array not fitting the byte boundary

I have the following array of bytes:
01010110 01110100 00100101 01001011
These bytes are broken into two groups to encode seven integers. I know that the first group consists of 3 values 4 bits each (0101 0110 0111) that represent numbers 5,6,7. The second group consists of 4 values 5 bits each (01000 01001 01010 01011), which represent integers 8,9,10, and 11.
To extract the integers, I am currently using the following approach. Convert the array into a binary string:
public static String byteArrayToBinaryString(byte[] byteArray)
{
String[] arrayOfStrings = new String[byteArray.length];
for(int i=0; i<byteArray.length; i++)
{
arrayOfStrings[i] = byteToBinaryString(byteArray[i]);
}
String bitsetString = "";
for(String testArrayStringElement : arrayOfStrings)
{
bitsetString += testArrayStringElement;
}
return bitsetString;
}
// Taken from here: http://helpdesk.objects.com.au/java/converting-large-byte-array-to-binary-string
public static String byteToBinaryString(byte byteIn)
{
StringBuilder sb = new StringBuilder("00000000");
for (int bit = 0; bit < 8; bit++)
{
if (((byteIn >> bit) & 1) > 0)
{
sb.setCharAt(7 - bit, '1');
}
}
return sb.toString();
}
Then, I split the binary string into 2 substrings: 12 characters and 20 characters. Then I split each substring into new substrings, each of which has length that equals the number of bits. Then I convert each sub-substring into an integer.
It works but a byte array representing thousands of integers takes 30 seconds to a minute to extract.
I am a bit at a loss here. How do I do this using bitwise operators?
Thanks a lot!
I assume you have an understanding of the basic bit operations and how to express them in Java.
Use a pencil to draw a synthetic picture of the problem
byte 0 byte 1 byte 2 byte 3
01010110 01110100 00100101 01001011
\__/\__/ \__/\______/\___/\______/\___/
a b c d e f g
To extract a, b and c we need to do the following
a b c
byte 0 byte 0 byte 1
01010110 01010110 01110100
\. \. |||||||| \. \.
'\ '\ XXXX|||| '\ '\
0.. 0101 0.. 0110 0.. 0111
Shift And Shift
In Java
int a = byteArray[0] >>> 4, b = byteArray[0] & 0xf, c = byteArray[1] >>> 4;
The other values d, e, f and g are computed similarly but some of them require to read two bytes from the array (d and f actually).
d e
byte 1 byte 2 byte 2
01110100 00100101 00100101
||||\\\\ | |\\\\\
XXXX \\\\ | X \\\\\
\\\\| \\\\\
0.. 01000 01001
To compute d we need to isolate the least four bits of byte 1 with byteArray[1] & 0xf then make space for the bit from byte 2 with (byteArray[1] & 0xf) << 1, extract that bit with byteArray[1] >>> 7 and finally merge together the result.
int d = (byteArray[1] & 0xf) << 1 | byteArray[2] >>> 7;
int e = (byteArray[2] & 0x7c) >>> 2;
int f = (byteArray[2] & 0x3) << 3 | byteArray[3] >>> 5;
int g = byteArray[3] & 0x1f;
When you are comfortable with handling bits operations you may consider generalizing the function that extract the integers.
I made function int extract(byte[] bits, int[] sizes, int[] res), that given an array of bytes bits, an array of sizes sizes, where the even indices hold the size of the integers to extract in bits and the odd indices the number of integers to extract, and an output array res large enough to hold all the integers in output, extracts from bits all the integers expressed by sizes.
It returns the number of integers extracted.
For example the original problem can be solved as
int res[] = new int[8];
byte bits[] = new byte[]{0x56, 0x74, 0x25, 0x4b};
//Extract 3 integers of 4 bits and 4 integers of 5 bits
int ints = BitsExtractor.extract(bits, new int[]{4, 3, 5, 4}, res);
public class BitsExtractor
{
public static int extract(byte[] bits, int[] sizes, int[] res)
{
int currentByte = 0; //Index into the bits array
int intProduced = 0; //Number of ints produced so far
int bitsLeftInByte = 8; //How many bits left in the current byte
int howManyInts = 0; //Number of integers to extract
//Scan the sizes array two items at a time
for (int currentSize = 0; currentSize < sizes.length - 1; currentSize += 2)
{
//Size, in bits, of the integers to extract
int intSize = sizes[currentSize];
howManyInts += sizes[currentSize+1];
int temp = 0; //Temporary value of an integer
int sizeLeft = intSize; //How many bits left to extract
//Do until we have enough integer or we exhaust the bits array
while (intProduced < howManyInts && currentByte <= bits.length)
{
//How many bit we can extract from the current byte
int bitSize = Math.min(sizeLeft, bitsLeftInByte); //sizeLeft <= bitsLeftInByte ? sizeLeft : bitsLeftInByte;
//The value to mask out the number of bit extracted from
//The current byte (e.g. for 3 it is 7)
int byteMask = (1 << bitSize) - 1;
//Extract the new bits (Note that we extract starting from the
//RIGHT so we need to consider the bits left in the byte)
int newBits = (bits[currentByte] >>> (bitsLeftInByte - bitSize)) & byteMask;
//Create the new temporary value of the current integer by
//inserting the bits in the lowest positions
temp = temp << bitSize | newBits;
//"Remove" the bits processed from the byte
bitsLeftInByte -= bitSize;
//Is the byte has been exhausted, move to the next
if (bitsLeftInByte == 0)
{
bitsLeftInByte = 8;
currentByte++;
}
//"Remove" the bits processed from the size
sizeLeft -= bitSize;
//If we have extracted all the bits, save the integer
if (sizeLeft == 0)
{
res[intProduced++] = temp;
temp = 0;
sizeLeft = intSize;
}
}
}
return intProduced;
}
}
Well I did the first group , the second can be done in similar fashion
public static void main(String args[]) {
//an example 32 bits like your example
byte[] bytes = new byte[4];
bytes[0] = 31;//0001 1111
bytes[1] = 54;//0011 0110
bytes[2] = 67;
bytes[3] = 19;
//System.out.println(bytes[0]);
int x = 0;
int j = -1; // the byte number
int k = 0; // the bit number in that byte
int n = 0; // the place of the bit in the integer we are trying to read
for (int i = 0; i < 32; i++) {
if (i < 12) { //first group
if (i % 8 == 0) {
j++;
k = 0;
}
if (i % 4 == 0) {
x = 0;
n = 0;
}
byte bit = (byte) ((bytes[j] & (1 << (7 - k))) >> (7 - k));
System.out.println("j is :" + j + " k is :" + k + " " + bit);
x = x | bit << (3 - n);
if ((i + 1) % 4 == 0) {
System.out.println(x);
}
k++;
n++;
} else {
}
}
}
It's a bit tricky because you are trying to encode an integer on less than what java allocates (8 bits). So I had to take each bit and "construct" the int from them
To get each bit
byte bit = (byte) ((bytes[j] & (1 << (7 - k))) >> (7 - k));
this takes the byte we are at and does And operation. For example I want the 3rd bit of the 1st byte, I do
bytes[0] & 1 << (7 - 3)
but this gives me an integer encoded over 8 bits, so I still have to shift it to get that single bit with >> (7 - 3)
Then I just Or it with x (the int we are trying to decode). All while putting it at the right position with << (3 - n) . 3 because your integer is encoded over 4 bits
Try running the code and reading the output.
I am honestly not sure if this is the best way, but I believe it's at least faster than dealing with Strings

how to perform xor operation correctly?

i have a binary string and i would like to perform a xor operation consequentially on several bits of that string.
my string is :
011001100011100000000011
i am trying to perform the calculation using the next line of code:
private String ParityCalc(String str){
char[] cA = str.toCharArray();
int[] D = new int[6];
D[0] = D29^cA[0]^cA[1]^cA[2]^cA[4]^cA[5]^cA[9]^cA[10]^cA[11]^cA[12]^cA[13]^cA[16]^cA[17]^cA[19]^cA[22];
D[1] = D30^cA[1]^cA[2]^cA[3]^cA[5]^cA[6]^cA[10]^cA[11]^cA[12]^cA[13]^cA[14]^cA[17]^cA[18]^cA[20]^cA[23];
D[2] = D29^cA[0]^cA[2]^cA[3]^cA[4]^cA[6]^cA[7]^cA[11]^cA[12]^cA[13]^cA[14]^cA[15]^cA[18]^cA[19]^cA[21];
D[3] = D30^cA[1]^cA[3]^cA[4]^cA[5]^cA[7]^cA[8]^cA[12]^cA[13]^cA[14]^cA[15]^cA[16]^cA[19]^cA[20]^cA[22];
D[4] = D30^cA[0]^cA[2]^cA[4]^cA[5]^cA[6]^cA[8]^cA[9]^cA[13]^cA[14]^cA[15]^cA[16]^cA[17]^cA[20]^cA[21]^cA[23];
D[5] = D29^cA[2]^cA[4]^cA[5]^cA[7]^cA[8]^cA[9]^cA[10]^cA[12]^cA[14]^cA[18]^cA[21]^cA[22]^cA[23];
for (int i = 0; i < 6; i++){
if (D[i] == 48){
D[i] = 0;
} else if (D[i] == 49){
D[i] = 1;
}
}
StringBuilder parity = new StringBuilder();
parity.append(D[0]).append(D[1]).append(D[2]).append(D[3]).append(D[4]).append(D[5]);
D29 = D[4];
D30 = D[5];
return parity.toString();
}
the result that i am getting for the final parity is: 100000.
the correct result should be: 001001.
the D29 and D30 are parity bits carried on from previous calculations, both are integers.
what am i doing wrong and how can i fix it? i should probably do it as a bitwise operation but i cant seem to figure it out.
any help would be appreciated.
That would be my approach:
private String ParityCalc(String str){
int input = Integer.parseInt(str,2);
int[] D = new int[6];
D[0] = input & (int)0x4b3e37; // Mask for indices 0,1,2,4,5,9,10,11,12,13,16,17,19,22
D[0] = (Integer.bitCount(D[0])&0x1)^D29; // Parity of masked input XOR D29
// D[1-5] accordingly
StringBuilder parity = new StringBuilder();
parity.append(D[0]).append(D[1]).append(D[2]).append(D[3]).append(D[4]).append(D[5]);
D29 = D[4];
D30 = D[5];
return parity.toString();
}
Mask: 0,1,2,4,5,9,10,11,12,13,16,17,19,22
3 3 2 1
210987654321098765432109876543210 "Position"
000000000010010110011111000110111 BIN
0 0 4 B 3 E 3 7 Hex (4 digits bin = 1 Hex)
I've tried following code, it it what you want?
public static void xor () {
final String a = "011001100011100000000011";
final String b = a.substring(3, 7);
final long ai = Long.parseLong(a, 2);
final long bi = Long.parseLong(b, 2);
final long la = Long.toBinaryString(ai).length();
final long lb = Long.toBinaryString(bi).length();
long i,j,fa,fb,fo,result = ai;
for (i = 0; i < lb; ++ i) {
// get most significant bit one by one; a
fb = 1l & (bi >> (lb - i - 1l));
for (j = 0; j < la; ++ j) {
// get most significant bit one by one; b
fa = 1l & (ai >> (la - j - 1l));
// one ^ one
fo = fa ^ fb;
if (0 == fo) {
// & 0
result &= ((-1l << la - j) | ((1l << (la - j - 1)) - 1));
} else {
// | 1
result |= (1l << (la - j - 1l));
}
}
}
System.out.println(result);
}
Solution:
Xor each bit of two binary string(will be converted to integer) and reset each bit back to original integer that converted from original binary string (can be a new integer, it depends).
Please let me know, if any problem.

Bit shift operations on a byte array in Java

How do I shift a byte array n positions to the right? For instance shifting a 16 byte array right 29 positions? I read somewhere it can be done using a long? Would using a long work like this:
Long k1 = byte array from 0 to 7
Long k2 = byte array from 8 to 15
Then right rotating these two longs using Long.rotateRight(Long x, number of rotations).How would the two longs be joined back into a byte array?
I believe you can do this using java.math.BigInteger which supports shifts on arbitrarily large numbers. This has advantage of simplicity, but disadvantage of not padding into original byte array size, i.e. input could be 16 bytes but output might only be 10 etc, requiring additional logic.
BigInteger approach
byte [] array = new byte[]{0x7F,0x11,0x22,0x33,0x44,0x55,0x66,0x77};
// create from array
BigInteger bigInt = new BigInteger(array);
// shift
BigInteger shiftInt = bigInt.shiftRight(4);
// back to array
byte [] shifted = shiftInt.toByteArray();
// print it as hex
for (byte b : shifted) {
System.out.print(String.format("%x", b));
}
Output
7f1122334455667 <== shifted 4 to the right. Looks OK
Long manipulation
I don't know why you'd want to do this as rotateRight() as this makes life more difficult, you have to blank at the bits that appear at the left hand side in K1 etc. You'd be better with using shift IMO as describe below. I've used a shift of 20 as divisible by 4 so easier to see the nibbles move in the output.
1) Use ByteBuffer to form two longs from 16 byte array
byte[] array = { 0x00, 0x00, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77 };
ByteBuffer buffer = ByteBuffer.wrap(array);
long k1 = buffer.getLong();
long k2 = buffer.getLong();
2) Shift each long n bits to the right
int n = 20;
long k1Shift = k1 >> n;
long k2Shift = k2 >> n;
System.out.println(String.format("%016x => %016x", k1, k1Shift));
System.out.println(String.format("%016x => %016x", k2, k2Shift));
0000111122223333 => 0000000001111222
4444555566667777 => 0000044445555666
Determine bits from k1 that "got pushed off the edge"
long k1CarryBits = (k1 << (64 - n));
System.out.println(String.format("%016x => %016x", k1, k1CarryBits));
0000111122223333 => 2333300000000000
Join the K1 carry bits onto K2 on right hand side
long k2WithCarray = k2Shift | k1CarryBits;
System.out.println(String.format("%016x => %016x", k2Shift, k2WithCarray));
0000044445555666 => 2333344445555666
Write the two longs back into a ByteBuffer and extract as a byte array
buffer.position(0);
buffer.putLong(k1Shift);
buffer.putLong(k2WithCarray);
for (byte each : buffer.array()) {
System.out.print(Long.toHexString(each));
}
000011112222333344445555666
Here is what I came up with to shift a byte array by some arbitrary number of bits left:
/**
* Shifts input byte array len bits left.This method will alter the input byte array.
*/
public static byte[] shiftLeft(byte[] data, int len) {
int word_size = (len / 8) + 1;
int shift = len % 8;
byte carry_mask = (byte) ((1 << shift) - 1);
int offset = word_size - 1;
for (int i = 0; i < data.length; i++) {
int src_index = i+offset;
if (src_index >= data.length) {
data[i] = 0;
} else {
byte src = data[src_index];
byte dst = (byte) (src << shift);
if (src_index+1 < data.length) {
dst |= data[src_index+1] >>> (8-shift) & carry_mask;
}
data[i] = dst;
}
}
return data;
}
1. Manually implemented
Here are left and right shift implementation without using BigInteger (ie. without creating a copy of the input array) and with unsigned right shift (BigInteger only supports arithmetic shifts of course)
Left Shift <<
/**
* Left shift of whole byte array by shiftBitCount bits.
* This method will alter the input byte array.
*/
static byte[] shiftLeft(byte[] byteArray, int shiftBitCount) {
final int shiftMod = shiftBitCount % 8;
final byte carryMask = (byte) ((1 << shiftMod) - 1);
final int offsetBytes = (shiftBitCount / 8);
int sourceIndex;
for (int i = 0; i < byteArray.length; i++) {
sourceIndex = i + offsetBytes;
if (sourceIndex >= byteArray.length) {
byteArray[i] = 0;
} else {
byte src = byteArray[sourceIndex];
byte dst = (byte) (src << shiftMod);
if (sourceIndex + 1 < byteArray.length) {
dst |= byteArray[sourceIndex + 1] >>> (8 - shiftMod) & carryMask;
}
byteArray[i] = dst;
}
}
return byteArray;
}
Unsigned Right Shift >>>
/**
* Unsigned/logical right shift of whole byte array by shiftBitCount bits.
* This method will alter the input byte array.
*/
static byte[] shiftRight(byte[] byteArray, int shiftBitCount) {
final int shiftMod = shiftBitCount % 8;
final byte carryMask = (byte) (0xFF << (8 - shiftMod));
final int offsetBytes = (shiftBitCount / 8);
int sourceIndex;
for (int i = byteArray.length - 1; i >= 0; i--) {
sourceIndex = i - offsetBytes;
if (sourceIndex < 0) {
byteArray[i] = 0;
} else {
byte src = byteArray[sourceIndex];
byte dst = (byte) ((0xff & src) >>> shiftMod);
if (sourceIndex - 1 >= 0) {
dst |= byteArray[sourceIndex - 1] << (8 - shiftMod) & carryMask;
}
byteArray[i] = dst;
}
}
return byteArray;
}
Used in this class by this Project.
2. Using BigInteger
Be aware that BigInteger internally converts the byte array into an int[] array so this may not be the most optimized solution:
Arithmetic Left Shift <<:
byte[] result = new BigInteger(byteArray).shiftLeft(3).toByteArray();
Arithmetic Right Shift >>:
byte[] result = new BigInteger(byteArray).shiftRight(2).toByteArray();
3. External Library
Using the Bytes java library*:
Add to pom.xml:
<dependency>
<groupId>at.favre.lib</groupId>
<artifactId>bytes</artifactId>
<version>{latest-version}</version>
</dependency>
Code example:
Bytes b = Bytes.wrap(someByteArray);
b.leftShift(3);
b.rightShift(3);
byte[] result = b.array();
*Full Disclaimer: I am the developer.
The is an old post, but I want to update Adam's answer.
The long solution works with a few tweak.
In order to rotate, use >>> instead of >>, because >> will pad with significant bit, changing the original value.
second, the printbyte function seems to miss leading 00 when it prints.
use this instead.
private String getHexString(byte[] b) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < b.length; i++)
result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)
.substring(1));
return result.toString();
}

Convert each character of a string in bits

String message= "10";
byte[] bytes = message.getBytes();
for (int n = 0; n < bytes.length; n++) {
byte b = bytes[n];
for (int i = 0; i < 8; i++) {//do something for each bit in my byte
boolean bit = ((b >> (7 - i) & 1) == 1);
}
}
My problem here is that it takes 1 and 0 as their ASCII values, 49 and 48, instead of 1 and 0 as binary(00000001 and 00000000). How can I make my program treat each character from my string as a binary sequence of 8 bits?
Basicly, I want to treat each bit of my number as a byte. I do that like this byte b = bytes[n]; but the program treats it as the ASCII value.
I could assign the number to an int, but then, I can't assign the bits to a byte.
It's a bit messy, but the first thing that comes to mind is to first, split your message up into char values, using the toCharArray() method. Next, use the Character.getNumericValue() method to return the int, and finally Integer.toBinaryString.
Example
String message = "123456";
for(char c : message.toCharArray())
{
int numVal = Character.getNumericValue(c);
String binaryString = Integer.toBinaryString(numVal);
for(char bit : binaryString)
{
// Do something with your bits.
}
}
String msg = "1234";
for(int i=0 ; i<msg.length() ; i++ ){
String bits = Integer.toBinaryString(Integer.parseInt(msg.substring(i, i+1)));
for(int j=0;j<8-bits.length();j++)
bits = "0"+bits;
}
Now bits is a string of length 8.
1
00000001
10
00000010
11
00000011
100
00000100
You can use getBytes() on the String
Use Java's parseInt(String s, int radix):
String message= "10";
int myInt = Integer.parseInt(message, 2); //because we are parsing it as base 2
At that point you have the correct sequence of bits, and you can do your bit-shifting.
boolean[] bits = new boolean[message.length()];
System.out.println("Parsed bits: ");
for (int i = message.length()-1; i >=0 ; i--) {
bits[i] = (myInt & (1 << i)) != 0;
System.out.print(bits[i] ? "1":"0");
}
System.out.println();
You could make it bytes if you really want to, but booleans are a better representation of bits...

Print an integer in binary format in Java

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.
Is there any built-in function for that in Java?
Assuming you mean "built-in":
int x = 100;
System.out.println(Integer.toBinaryString(x));
See Integer documentation.
(Long has a similar method, BigInteger has an instance method where you can specify the radix.)
Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)
Integer.toString(100,8) // prints 144 --octal representation
Integer.toString(100,2) // prints 1100100 --binary representation
Integer.toString(100,16) //prints 64 --Hex representation
System.out.println(Integer.toBinaryString(343));
I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:
n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
So here's what I wrote:
/**
* Converts an integer to a 32-bit binary string
* #param number
* The number to convert
* #param groupSize
* The number of bits in a group
* #return
* The 32-bit long bit string
*/
public static String intToString(int number, int groupSize) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
if (i % groupSize == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
Invoke it like this:
public static void main(String[] args) {
System.out.println(intToString(5463, 4));
}
public static void main(String[] args)
{
int i = 13;
short s = 13;
byte b = 13;
System.out.println("i: " + String.format("%32s",
Integer.toBinaryString(i)).replaceAll(" ", "0"));
System.out.println("s: " + String.format("%16s",
Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));
System.out.println("b: " + String.format("%8s",
Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));
}
Output:
i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101
Old school:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
Output (least significant bit is on 0 position):
0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0
check out this logic can convert a number to any base
public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;
number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}
OR
StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
if((n&1)==1){
binary.append(1);
}else
binary.append(0);
n>>=1;
}
System.out.println(binary.reverse());
This is the simplest way of printing the internal binary representation of an integer.
For Example: If we take n as 17 then the output will be: 0000 0000 0000 0000 0000 0000 0001 0001
void bitPattern(int n) {
int mask = 1 << 31;
int count = 0;
while(mask != 0) {
if(count%4 == 0)
System.out.print(" ");
if((mask&n) == 0)
System.out.print("0");
else
System.out.print("1");
count++;
mask = mask >>> 1;
}
System.out.println();
}
Simple and pretty easiest solution.
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}
Solution using 32 bit display mask,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110
Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.
public static void printBinaryNumbers(int n) {
char[] arr = Integer.toBinaryString(n).toCharArray();
StringBuilder sb = new StringBuilder();
for (Character c : arr) {
sb.append(c);
}
System.out.println(sb);
}
input
5
Output
101
There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based → modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001
Binary representation of given int x with left padded zeros:
org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')
You can use bit mask (1<< k) and do AND operation with number!
1 << k has one bit at k position!
private void printBits(int x) {
for(int i = 31; i >= 0; i--) {
if((x & (1 << i)) != 0){
System.out.print(1);
}else {
System.out.print(0);
}
}
System.out.println();
}
The question is tricky in java (and probably also in other language).
A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.
So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).
The safe way is to use Integer.toString(X,2); this will generate something less elegant:
-11110100110
But it works!!!
I think it's the simplest algorithm so far (for those who don't want to use built-in functions):
public static String convertNumber(int a) {
StringBuilder sb=new StringBuilder();
sb.append(a & 1);
while ((a>>=1) != 0) {
sb.append(a & 1);
}
sb.append("b0");
return sb.reverse().toString();
}
Example:
convertNumber(1) --> "0b1"
convertNumber(5) --> "0b101"
convertNumber(117) --> "0b1110101"
How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).
for(int i = 1; i <= 256; i++)
{
System.out.print(i + " "); //show integer
System.out.println(Integer.toBinaryString(i) + " "); //show binary
System.out.print(Integer.toOctalString(i) + " "); //show octal
System.out.print(Integer.toHexString(i) + " "); //show hex
}
Try this way:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number.
Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number.
The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int integer ;
String binary = ""; // here we count "" or null
// just String binary = null;
System.out.print("Enter the binary Number: ");
integer = sc.nextInt();
while(integer>0)
{
int x = integer % 2;
binary = x + binary;
integer = integer / 2;
}
System.out.println("Your binary number is : "+binary);
System.out.println("your binary length : " + binary.length());
}
}
Since no answer is accepted, maybe your question was about how to store an integer in an binary-file.
java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html
DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();
Integer.toString(value,numbersystem) --- syntax to be used
and pass value
Integer.toString(100,8) // prints 144 --octal
Integer.toString(100,2) // prints 1100100 --binary
Integer.toString(100,16) //prints 64 --Hex
This is my way to format an output of the Integer.toBinaryString method:
public String toBinaryString(int number, int groupSize) {
String binary = Integer.toBinaryString(number);
StringBuilder result = new StringBuilder(binary);
for (int i = 1; i < binary.length(); i++) {
if (i % groupSize == 0) {
result.insert(binary.length() - i, " ");
}
}
return result.toString();
}
The result for the toBinaryString(0xABFABF, 8) is "10101011 11111010 10111111"
and for the toBinaryString(0xABFABF, 4) is "1010 1011 1111 1010 1011 1111"
It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}
`
long k=272214023L;
String long =
String.format("%64s",Long.toBinaryString(k)).replace(' ','0');
String long1 = String.format("%64s",Long.toBinaryString(k)).replace(' ','0').replaceAll("(\d{8})","$1 ");
`
print :
0000000000000000000000000000000000000000000
00000000 00000000 00000000 00000000 0000000

Categories