How to separate and rotate numbers in integer? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a small problem. I think it's simple, but I don't know, how to manage it properly.
I have this simple int:
int birth = 011112;
and I want output to look like this, in this specific format.
"Your birth date is 12.11.01."
I did it with an integer array, but I want only one integer input like this one, not an array.
Could some body help me? Is there any simple method to manage it of, without using loops?

Basically, the conversion of the int representing a date in some format into String should use divide / and modulo % operations, conversion to String may use String.format to provide leading 0.
The number starting with 0 is written in octal notation, where the digits in range 0-7 are used, so the literals like 010819 or 080928 cannot even be written in Java code as int because of the compilation error:
error: integer number too large
int birth = 010819;
However, (only for the purpose of this exercise) we may assume that the acceptable octal numbers start with 01 or 02 then such numbers are below 10000 decimal.
Then the numeric base for division/modulo and the type of output (%d for decimal or %o for octal) can be defined:
public static String rotate(int x) {
int base = x < 10000 ? 0100 : 100;
String type = x < 10000 ? "o" : "d";
int[] d = {
x % base,
x / base % base,
x / (base * base)
};
return String.format("%02" + type + ".%02" + type + ".%02" + type, d[0], d[1], d[2]);
}
Tests:
System.out.println(rotate(011112)); // octal
System.out.println(rotate(11112)); // decimal (no leading 0)
Output:
12.11.01
12.11.01

Related

retrieve number from hex string in variable length [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a hex string format below:
2828287798519497FFFF9000 => 2828287798519497 (result)
1122334466667788996FFFF9000 => 1122334466667788996 (result)
which the id is length in between 16 – 19, where right most is fill with 0xF.
What is 0xF?
How can I get id number, wither it is 16, 17, 18 or 19 length from the hex string above?
BigInteger is for arbitrary precision integral math, and it has a constructor that takes a String and an int radix. 0xF is the sixteenth value in base 16 (digits are the usual zero to nine of base-10 and the values A, B, C, D, E and F).
System.out.println(new BigInteger("2828287798519497FFFF9000", 16));
System.out.println(new BigInteger("1122334466667788996FFFF9000", 16));
The base-10 representation of your two values is thus
12427948526435964620659200000
21719411700849473095611778568192
Based on the examples you gave, the ID number you want consists of all but the last eight characters of the given hex string (which are FFFF9000 in both example cases). In other words, a substring starting at the beginning of the string and extending up to, but not including, the eight-to-last character:
String h = "2828287798519497FFFF9000";
String id = h.substring(0, h.length()-8);
System.out.println(h + " => " + id);

Large amount of decimal digits to ASCII [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am reading a number from a file, and I want to convert it to an ASCII text string. I've seen questions relating to this but they all were dealing with single decimal-equivalent ASCII values, like 12 to ASCII, 87 to ASCII, 112 to ASCII, etc. I need to convert a large amount of decimals with no spaces into ASCII text. Can anyone show me how this is done? How would the system ascertain whether the first number to translate is 1, 12, or 123?
For example:
int intval = 668976111;
//CONVERSION CODE
System.out.println(newval);
prints "bylo"
If the int 123, how would it know if I was saying 1,2,3 or 12,3 or 123 or 1,23 etc? How can I convert decimal numbers like this to Unicode characters?
Try this.
static void decode(String s, int index, byte[] decode, int size) {
if (index >= s.length())
System.out.println(new String(decode, 0, size));
else
for (int i = index + 1; i <= s.length(); ++i) {
int d = Integer.parseInt(s.substring(index, i));
if (Character.isISOControl(d)) continue;
if (d > 255) break;
decode[size] = (byte)d;
decode(s, i, decode, size + 1);
}
}
static void decode(String s) {
decode(s, 0, new byte[s.length()], 0);
}
and
decode("668976111"); // -> BYLo
This is a kinda hard problem, as ascii codes can be single, two or three digit long.
Now if your encoding only alphadecimal characters and characters above the decimal number 20 it is pretty easy.
The algorithm wouild be as follows. Iterate through the array(a digit is an element of the array), if the first number is 1, take 3 numbers, as you cant have a char with code less than 20. If the first number is higher than 20, take only 2 numbers.
This way you will get the right decoding, assuming you dont have anything encoded with codes less than 20, which is a very possible assumption, as the first "useful" code is at number 32, which is space

How to convert large integer number to binary?

Sorry for a possible duplicate post, I saw many similar topics here but none was exactly I needed. Before actually posting a question I want to explicitly state that this question is NOT A HOMEWORK.
So the question is: how to convert a large integer number into binary representation? The integer number is large enough to fit in primitive type (Java long cannot be used). An input might be represented as a string format or as an array of digits. Disclaimer, This is not going to be a solution of production level, so I don't want to use BigInteger class. Instead, I want to implement an algorithm.
So far I ended up with the following approach:
Input and output values represented as strings. If the last digit of input is even, I prepend the output with "0", otherwise - with "1". After that, I replace input with input divided by 2. I use another method - divideByTwo for an arithmetical division. This process runs in a loop until input becomes "0" or "1". Finally, I prepend input to the output. Here's the code:
Helper Method
/**
* #param s input integer value in string representation
* #return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
Main Method
/**
* #param s the integer in string representation
* #return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
As you can see, the runtime is O(n^2). O(n) for integerToBinary method and O(n) for divideByTwo that runs inside the loop. Is there a way to achieve a better runtime? Thanks in advance!
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
Among the simple methods there are two possible approaches (all numbers that appear here decimal)
work in decimal and divide by 2 in each step as you outlined in the question
work in binary and multiply by 10 in each step for example 123 = ((1 * 10) + 2) * 10 + 3
If you are working on a binary computer the approach 2 may be easier.
See for example this post for a more in-depth discussion of the topic.
In wikipedia, it is said:
For very large numbers, these simple methods are inefficient because
they perform a large number of multiplications or divisions where one
operand is very large. A simple divide-and-conquer algorithm is more
effective asymptotically: given a binary number, it is divided by
10^k, where k is chosen so that the quotient roughly equals the
remainder; then each of these pieces is converted to decimal and the
two are concatenated. Given a decimal number, it can be split into two
pieces of about the same size, each of which is converted to binary,
whereupon the first converted piece is multiplied by 10^k and added to
the second converted piece, where k is the number of decimal digits in
the second, least-significant piece before conversion.
I have tried, this method is faster than conventional one for numbers larger than 10,000 digits.

convert float to short with minimal loss of precision [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this sine wave which generates floating point values (e.g. 0.37885) but I want them as shorts. Direct casting with short gives me a value of 0. so what is the solution?
Can anyone tell me how to do it - ideally without loss of precision - or minimal loss of precision if this is all that is possible?
public static short floatToShort(float x) {
if (x < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
if (x > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
return (short) Math.round(x);
}
You'll loose the fractional part:
float 4 byte floating-point
double 8 byte floating-point (normal)
short 2 byte integer
int 4 byte integer (normal)
long 8 byte integer
Edit:
Maybe you wanted to know how to save the bits of a float (4 bytes) into an int (4 bytes):
(http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#floatToRawIntBits(float))
float x = 0.1f;
int n = Float.floatToRawIntBits(x);
float y = Float.intBitsToFloat(n);
In principle, you could just multiply it by 100000, convert it to int, then subtract -32,767 and convert it to short. If that still puts it in the -32,767 to 32,767 range for all your values, that's likely the best you can do. Otherwise, you'll have to limit your precision and multiply by 10000.
And when you use the short of course you have to remember to divide it back down.
If your input float values are in a defined range (for now let's assume they're in the range of -1..1, exclusive), you can multiply them to get a value whose fraction you'll throw away.
Valid short range is: -32768..32767 so you can multiple with 32768 in this case (max short / max input value).
For example:
float f = 0.23451f;
short s = (short) (f * 32768);
To decode a short value to float:
float f2 = s / 32768f;
short is an integral type, so it can only contain whole numbers. The only two choices for 0.37885 in a short are 0 or 1, both of which (it seems to me) lose quite a bit of precision.
So the answer is: If you're okay with losing all fractional values, either use a cast, Float#shortValue, or Math.round(float) (and cast the resulting int to short).
Example: Live Copy
float f1 = 0.37885f;
short s1 = (short)Math.round(f1);
System.out.println("s1 = " + s1);
float f2 = 27.67885f;
short s2 = (short)Math.round(f2);
System.out.println("s2 = " + s2);
Output:
s1 = 0
s2 = 28
In a comment you said:
I have this sine wave which generates values like the one mentioned above, but I want them as shorts.
Ah, now, we can do something with that. Presumably the values you're getting are all between 0 and 1. You can store them as shorts by multiplying. Since the range of a short is -32,768 to 37,767, a convenient number to multiply them by might be 10000:
short s = Math.round(floatValue * 10000);
The number we'd get for your example would be 3789. Example: Live Copy
float floatValue = 0.37885f;
short s = (short)Math.round((double)floatValue * 10000);
System.out.println("s = " + s);
That isn't the same value, of course, it's the value multipled by ten thousand, so anywhere you're going to use it, you'd have to allow for that.

Meaning of the asterisk symbol in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to change the meaning of the asterisk symbol (multiplication operator) in Java?
I want to do this:
int ex = 600 * 0.98;
It fails because you can't convert from double to int. Can I make it so that I'm able to convert the double to an integer? Or does the
asterisk only have one meaning that can't be changed?
I just want the OPERATION in math, not a string.
To have an operation, you must have code. One way of doing this is to have a method like
public static double ex(double factor) {
return factor * 0.98;
}
or if the factor is a field
private double factor = 600;
public double ex() {
return factor * 98 / 100;
}
public static void main(String... ignored) {
Main m = new Main();
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
m.factor = 700;
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
}
prints
factor: 600.0 ex: 588.0
factor: 700.0 ex: 686.0
As you can see ex() is re-evaluated each time it is used.
Why do I * 98 / 100? I do this as each value can be represented exactly however 0.98 is not represent exactly and can have a small error.
System.out.println(new BigDecimal(0.98));
prints the closest representable value to 0.98
0.979999999999999982236431605997495353221893310546875
If you want to store text you need to do something like
String ex = "600 * 0.98";
An int value is for storing a whole number which is a 32-bit signed value, nothing else.
Uhhh.
The short answer is that you can't do that. A variable of type int can only store an integer value. The expression you assign to the int has to evaluate to an integer.
What integer value do you want assigned to ex?
int ex = 588; // 600 * 0.98
What meaning are you associating with the asterisk between two numeric values that is not multiplication?
If you want to store an array of characters, then:
char[] ex = "600 * 0.98".toCharArray();

Categories

Resources