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.
Related
How to efficiently save and access a large array of 5 bit numbers in memory?
For example
01100
01101
01110
01111
10000
10001
which I will later convert to a byte to check what number it is?
I was thinking of just using an array of bytes but after a while this will be wasting a lot of memory as this will be a continually growing array. Also I will want to save this array efficiently. I will only be using exactly 5 bits.
This is the code that I use for a bit array implementation in C, in JAVA it's going to be the same, I must reconsider what I said about the list, maybe an array is going to be better.
Anyway, you consider the array as a contiguous segments of bits. Those functions set, get, and read the k-th bit of the array. In this case I'm using an array of integers, so you see '32', is you use an array of bytes, then you'd use '8'.
void set_bit(int a[], int k)
{
int i = k / 32;
int pos = k % 32;
unsigned int flag = 1; // flag = 0000....00001
flag = flag << pos; // flag = 0000...00100..0000
a[i] = a[i] | flag; // set the bit at the k-th position in a[i]
}
void clear_bit(int a[], int k)
{
int i = k / 32;
int pos = k % 32;
unsigned int flag = 1; // flag = 0000....00001
flag = flag << pos; // flag = 0000...00100..0000
flag = ~flag;
a[i] = a[i] & flag; // set the bit at the k-th position in a[i]
}
int test_bit(int a[], int k)
{
int i = k / 32;
int pos = k % 32;
unsigned int flag = 1; // flag = 0000....00001
flag = flag << pos; // flag = 0000...00100..0000
if (a[i] & flag) // test the k-th bit of a to be 1
return 1;
else
return 0;
}
I don't know how you store the five bits number, you'll have to insert them bit by bit, and also keep track of the last empty position in the bit array.
"I was thinking of just using an array of bytes but after a while this will be wasting a lot of memory as this will be a continually growing array."
I've dealt with a similar problem and decided to write a file based BitInputStream and a BitOutputSteam. Therefore running out of memory was no longer an issue. Please note that the given links are not my work but good examples of how to write a bit input/output stream.
I wrote an implementation of a 5-bit byte vector on top of an 8-bit byte vector in Javascript some time ago that might be of some help.
const ByteVector = require('bytevector');
class FiveBuffer {
constructor(buffer = [0], bitsAvailable = 8) {
this.buf = new ByteVector(buffer);
this.bitsAvailable = bitsAvailable;
this.size = Math.floor(((this.byteSize() * 8) - this.bitsAvailable) / 5);
}
push(num) {
if (num > 31 || num < 0)
throw new Error(`Only 5-bit unsigned integers (${num} not among them) are accepted`);
var firstShift = 5 - this.bitsAvailable;
var secondShift = this.bitsAvailable + 3;
var firstShifted = shiftRight(num, firstShift);
var backIdx = this.buf.length - 1;
var back = this.buf.get(backIdx);
this.buf.set(backIdx, back | firstShifted);
if (secondShift < 8) {
var secondShifted = num << secondShift;
this.buf.push(secondShifted);
}
this.bitsAvailable = secondShift % 8;
this.size++;
}
get(idx) {
if (idx > this.size)
throw new Error(`Index ${idx} is out of bounds for FiveBuffer of size ${this.size}`);
var bitIdx = idx * 5;
var byteIdx = Math.floor(bitIdx / 8);
var byte = this.buf.get(byteIdx);
var bit = bitIdx % 8;
var firstShift = 3 - bit;
var firstShifted = shiftRightDestroy(byte, firstShift);
var final = firstShifted;
var secondShift = 11 - bit;
if (secondShift < 8) {
var secondShifted = this.buf.get(byteIdx + 1) >> secondShift;
final = final | secondShifted;
}
return final;
}
buffer() {
this.buf.shrink_to_fit();
return this.buf.buffer();
}
debug() {
var arr = [];
this.buffer().forEach(x => arr.push(x.toString(2)));
console.log(arr);
}
byteSize() {
return this.buf.size();
}
}
function shiftRightDestroy(num, bits) {
var left = 3 - bits;
var res = (left > 0) ? ((num << left) % 256) >> left : num;
return shiftRight(res, bits);
}
function shiftRight(num, bits) {
return (bits < 0) ?
num << -bits :
num >> bits;
}
module.exports = FiveBuffer;
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;
}
I'm dealing with a problem to partition specific IP address ranges (in Java). Suppose I have:
startIP endIP
1.2.3.4 1.2.5.6
and I need cut this range into every [0, 255] interval so we have:
startIP endIP
1.2.3.4 1.2.3.255
1.2.4.0 1.2.4.255
1.2.5.0 1.2.5.6
I'm looking at this problem more or less like partitioning a decimal range for instance from 7 to 26 and we have [7, 9], [10, 19], [20, 26]. The only difference is we are dealing with 256-simal numbers. Any ideas, folks? Thank you!
You can use InetAddress for this, and run a straightforward loop to do the increments:
InetAddress from = InetAddress.getByName("1.2.3.4");
InetAddress to = InetAddress.getByName("1.2.5.6");
byte[] partsTo = to.getAddress();
for (;;) {
System.out.print(from+" - ");
byte[] parts = from.getAddress();
boolean sameUpperPart = true;
for (int i = 0 ; sameUpperPart && i < parts.length-1 ; i++) {
sameUpperPart &= (partsTo[i] == parts[i]);
}
if (sameUpperPart) {
System.out.println(to);
break;
}
int last = parts.length-1;
parts[last] = (byte)0xFF;
System.out.println(InetAddress.getByAddress(parts));
parts[last] = 0x00;
for (int i = last-1 ; i >= 0 ; i--) {
if (++parts[i] != 0) {
break;
}
}
from = InetAddress.getByAddress(parts);
}
This code produces the following output on ideone:
/1.2.3.4 - /1.2.3.255
/1.2.4.0 - /1.2.4.255
/1.2.5.0 - /1.2.5.6
Some sample code (assumes the initial translation to a int[] is done outside) and which doesn't really return useful data (just prints). But the idea is there.
public class Convertor {
public static void convert(int []a, int []b) {
int left = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3];
int right = left | 0xff;
int end = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
while ( right < end ) {
System.out.printf("%s -> %s\n", toIp(left), toIp(right));
left = right + 1; right += 256;
}
System.out.printf("%s -> %s\n", toIp(left), toIp(end));
}
private static String toIp(int value) {
return String.format("%d.%d.%d.%d",
value >> 24 & 0xFF,
value >> 16 & 0xFF,
value >> 8 & 0xFF,
value & 0xFF);
}
}
call site:
Convertor.convert(new int[]{1, 2, 3, 4}, new int[]{1, 2, 5, 6});
output:
1.2.3.4 -> 1.2.3.255
1.2.4.0 -> 1.2.4.255
1.2.5.0 -> 1.2.5.6
First convert the IP address into a single integer, then partition by just adding 256 repeatedly, and converting back to an IP address.
public class IPPartition {
public static void main(String[] args) {
String startIP = "1.2.3.4";
String endIP = "1.2.5.6";
long start = toLong(startIP);
long end = toLong(endIP);
long last = start;
long part = (start / 256 + 1) * 256;
for (; part < end; last = part, part += 256) {
System.out.println(toIP(last) + " " + toIP(part));
}
System.out.println(toIP(last) + " " + toIP(end));
}
private static long toLong(String ip) {
String[] tokens = ip.split("\\.");
long sum = 0;
for (int i = 0; i < 4; i++) {
sum *= 256;
sum += Integer.parseInt(tokens[i]);
}
return sum;
}
private static String toIP(long num) {
String result = "";
for (int i = 0; i < 4; i++) {
long section = num % 256;
result = section + result;
if (i < 3) result = "." + result;
num /= 256;
}
return result;
}
}
I used longs here just to be safe, but you might be able to use integers, I haven't tried it. There could also be some off-by-one errors or something, I haven't tested it thoroughly.
I wouldn't know the specific solution for Java, but there is an algorithm in C. It will partition the IP range to largest possible subnets and print them. The resulting ranges will be aligned on subnet boundaries.
#define NETWORK_ZEROS(ip, prefix) ((ip) & (0xffffffff << (32 - (prefix))))
#define NETWORK_ONES(ip, prefix) ((ip) | (~ (0xffffffff << (32 - (prefix)))))
void print_ip(unsigned long ip)
{
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
printf("%d.%d.%d.%d", bytes[3], bytes[2], bytes[1], bytes[0]);
}
void partition_ip(unsigned long start, unsigned long stop)
{
int i;
while (start < stop)
{
// Change the start of the loop to 24 if you
// need to align on /24 boundaries
for (i=0; i <= 32; i++)
{
if (NETWORK_ZEROS(start, i) == start &&
NETWORK_ONES(start, i) <= stop)
{
print_ip(NETWORK_ZEROS(start, i));
printf(" - ");
print_ip(NETWORK_ONES(start, i));
printf("\n");
start = NETWORK_ONES(start, i) + 1;
break;
}
}
}
}
To convert IP to binary number just do something like this
a.b.c.d => ((((a*256)+b)*256)+c)*256+d
or
ip = (a << 24) | (b << 16) | (c << 8) | d
if you want it to be more efficient by utilizing bit shifting.
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
Assume my system as 32 bit machine. Considering this if I use long int for n>63 I will get my value as 0. How to solve it?
double is perfectly capable of storing powers of two up to 1023 exactly. Don't let someone tell you that floating point numbers are somehow always inexact. This is a special case where they aren't!
double x = 1.0;
for (int n = 0; n <= 200; ++n)
{
printf("2^%d = %.0f\n", n, x);
x *= 2.0;
}
Some output of the program:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
...
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
Just wait around for a 256-bit compiler, then use int :-)
No, seriously, since you just want to start with 1 and keep doubling, your best bet is to get a big integer library like GNU MP.
You would do that with a piece of code like (untested):
#include <stdio.h>
#include "gmp.h"
int main (void) {
int i;
mpz_t num;
mpz_init_set_ui (num, 1);
for (i = 0; i <= 200; i++) {
printf ("2^%d = ", i);
mpz_out_str (NULL, 10, num);
printf ("\n");
mpz_mul_ui (num, num, 2);
}
return 0;
}
You could code up your own data structure of an array of longs with only two operations, double and print but I think it would be far easier to just use GMP.
If you do want to roll your own, have a look at this. It's a variation/simplification of some big integer libraries I've developed in the past:
#include <stdio.h>
#include <stdlib.h>
// Use 16-bit integer for maximum portability. You could adjust
// these values for larger (or smaller) data types. SZ is the
// number of segments in a number, ROLLOVER is the maximum
// value of a segment plus one (need to be less than the
// maximum value of your datatype divided by two. WIDTH is
// the width for printing (number of "0" characters in
// ROLLOVER).
#define SZ 20
#define ROLLOVER 10000
#define WIDTH 4
typedef struct {
int data[SZ];
} tNum;
// Create a number based on an integer. It allocates the segments
// then initialises all to zero except the last - that one is
// set to the passed-in integer.
static tNum *tNumCreate (int val) {
int i;
tNum *num = malloc (sizeof (tNum));
if (num == NULL) {
printf ("MEMORY ERROR\n");
exit (1);
}
for (i = 0; i < SZ - 1; i++) {
num->data[i] = 0;
}
num->data[SZ-1] = val;
}
// Destroy the number. Simple free operation.
static void tNumDestroy (tNum *num) {
free (num);
}
// Print the number. Ignores segments until the first non-zero
// one then prints it normally. All following segments are
// padded with zeros on the left to ensure number is correct.
// If no segments were printed, the number is zero so we just
// output "0". Then, no matter what, we output newline.
static void tNumPrint (tNum *num) {
int i, first;
for (first = 1, i = 0; i < SZ; i++) {
if (first) {
if (num->data[i] != 0) {
printf ("%d", num->data[i]);
first = 0;
}
} else {
printf ("%0*d", WIDTH, num->data[i]);
}
}
if (first) {
printf ("0");
}
printf ("\n");
}
// Double a number. Simplified form of add with carry. Carry is
// initialised to zero then we work with the segments from right
// to left. We double each one and add the current carry. If
// there's overflow, we adjust for it and set carry to 1, else
// carry is set to 0. If there's carry at the end, then we have
// arithmetic overflow.
static void tNumDouble (tNum *num) {
int i, carry;
for (carry = 0, i = SZ - 1; i >= 0; i--) {
num->data[i] = num->data[i] * 2 + carry;
if (num->data[i] >= ROLLOVER) {
num->data[i] -= ROLLOVER;
carry = 1;
} else {
carry = 0;
}
}
if (carry == 1) {
printf ("OVERFLOW ERROR\n");
exit (1);
}
}
// Test program to output all powers of 2^n where n is in
// the range 0 to 200 inclusive.
int main (void) {
int i;
tNum *num = tNumCreate (1);
printf ("2^ 0 = ");
tNumPrint (num);
for (i = 1; i <= 200; i++) {
tNumDouble (num);
printf ("2^%3d = ", i);
tNumPrint (num);
}
tNumDestroy (num);
return 0;
}
and its associated output:
2^ 0 = 1
2^ 1 = 2
2^ 2 = 4
2^ 3 = 8
2^ 4 = 16
2^ 5 = 32
2^ 6 = 64
2^ 7 = 128
2^ 8 = 256
2^ 9 = 512
: : : : :
2^191 = 3138550867693340381917894711603833208051177722232017256448
2^192 = 6277101735386680763835789423207666416102355444464034512896
2^193 = 12554203470773361527671578846415332832204710888928069025792
2^194 = 25108406941546723055343157692830665664409421777856138051584
2^195 = 50216813883093446110686315385661331328818843555712276103168
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
python supports big integers out of the box. At any linux prompt, run this:
$ python -c "for power in range(201): print power, 2**power"
0 1
1 2
2 4
3 8
4 16
5 32
6 64
<snip>
196 100433627766186892221372630771322662657637687111424552206336
197 200867255532373784442745261542645325315275374222849104412672
198 401734511064747568885490523085290650630550748445698208825344
199 803469022129495137770981046170581301261101496891396417650688
200 1606938044258990275541962092341162602522202993782792835301376
This can be easily made into a script if necessary. See any python tutorial.
It's been ages since I've used Java seriously, but: BigInteger class? It has all the usual mathematical (multiply, pow) and bitwise (shiftLeft) operations.
Your tagging is a little confusing though, which language did you prefer?
Use java.math.BigInteger.shiftLeft.
for (int i = 0; i <= 200; i++) {
System.out.format("%d = %s%n", i, BigInteger.ONE.shiftLeft(i));
}
Excerpt of output:
0 = 1
1 = 2
2 = 4
3 = 8
4 = 16
:
197 = 200867255532373784442745261542645325315275374222849104412672
198 = 401734511064747568885490523085290650630550748445698208825344
199 = 803469022129495137770981046170581301261101496891396417650688
200 = 1606938044258990275541962092341162602522202993782792835301376
If BigInteger is unavailable, you can also just manually do the multiplication and store it in a String.
String s = "1";
for (int i = 0; i < 200; i++) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for (char ch : s.toCharArray()) {
int d = Character.digit(ch, 10) * 2 + carry;
sb.append(d % 10);
carry = d / 10;
}
if (carry != 0) sb.append(carry);
s = sb.toString();
System.out.format("%d = %s%n", i + 1, sb.reverse());
}
(see full output)
In C/C++ I don't know of a standard way you can store integers that big, pax's solution is the rightway to go.
However for Java, you do have a way out, BigInteger
Use scheme!
1 => (expt 2 200)
1606938044258990275541962092341162602522202993782792835301376
in kotlin :
var x= readLine()!!.toInt()
var y=BigDecimal(1)
for (i in 1..x)
{
y *= BigDecimal(2)
}
println(DecimalFormat().format(y))
If unsigned long int is 64 bits then the largest value for 2^n that you can represent is 2^63 (i.e. n = 63):
unsigned long int x = (1UL << n); // n = 0..63