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
Related
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
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);
While working with some code base, I am trying to understand piece of code so as can work and customize it , I am able to understand almost 90% of the code flow. Here is the overall flow
Code is being used to generate 15 digit code (alphanumeric), first 3 digits are customer provided.
Initially code is generating 16 digit alphanumeric number and storing it in the cache.
Customer can generated any number of code by specifying quantity.
all customer generated codes are being generated from the 16 digit number (point 2). All code generated have numbers/ alphabets from that 16 digit alphanumeric number.
When some one try to use those codes, system is trying to validate if the provided code is valid or not.
I am struck at the logic used to determine if the provided code is valid or not, here is that piece of code, I am generating 6 code as a sample, in this case alphanumeric code being generated and stored in the cache is
initial-alphabet : M9W6K3TENDGSFAL4
Code generated based on initial-alphabet are
myList=[123-MK93-ES6D-36F3, 123-MK93-EFTW-D3LG, 123-MK93-EALK-TGLD, 123-MK93-ELKK-DN6S, 123-MK93-E4D9-3A6T, 123-MK93-EMTW-LNME]
protected int getVoucherNumber(String voucherCode){
int voucherNumberPos = voucherCode.length() - 12;
String voucherNumberHex = voucherCode.substring(voucherNumberPos, voucherNumberPos + 6);
int firstByte = getIntFromHexByte(voucherNumberHex.substring(0, 2), 0);
int secondByte = getIntFromHexByte(voucherNumberHex.substring(2, 4), 1);
int thirdByte = getIntFromHexByte(voucherNumberHex.substring(4, 6), 7);
return firstByte << 16 | secondByte << 8 | thirdByte;
}
private int getIntFromHexByte(String value, int offset){
return (getIntFromHexNibble(value.charAt(0), offset) << 4) + getIntFromHexNibble(value.charAt(1), offset + 4);
}
private int getIntFromHexNibble(char value, int offset){
int pos = getAlphabet().indexOf(value);
if (pos == -1) {// nothing found}
pos -= offset;
while (pos < 0) {
pos += 16;
}
return pos % 16;
}
Here is the code which is trying to validate code
int voucherNumber = getVoucherNumber(kyList.get(4));
In this case value of voucherNumber is 4 i.e the fourth element from the list, in case I pass any value which is not part of the list getVoucherNumber method is returning a higher value (greater than the list count).
One of the main thing which confusing me are these 2 lines
int voucherNumberPos = voucherCode.length() - 12;
String voucherNumberHex = voucherCode.substring(voucherNumberPos, voucherNumberPos + 6);
As per my understanding, they are first moving out the first 3 digit from the check which are customer supplied but again they have not used rest of the string but only specific part of the string.
Can any one help me to understand this
It appears you've inherited responsibility for some poorly written code. We've all been there so I'll try to answer in that spirit. I'm not positive this question is on-topic for this site, but it doesn't appear to be forbidden by the help center. In an attempt to stay on-topic I'll end with some general advice not limited to the highly-localized specifics of the question.
myList.get(4)
Arrays in Java are zero-based, so that's 123-MK93-E4D9-3A6T. You probably know that, but it isn't clear from your question that you do.
initial-alphabet : M9W6K3TENDGSFAL4
I assume this is what's returned by the call to getAlphabet in getIntFromHexNibble. So the alphanumeric characters in the code are meant to be hexadecimal but using a nonstandard set of 16 characters for the digits.
protected int getVoucherNumber(String voucherCode){
Ignoring the hyphens and the customer-supplied first three digits, the code is 'MK93E4D93A6T'. Twelve hex digits encode 48 bits, but an int in Java is only 32 bits long, so the code is already broken. Whatever it does, it isn't going to return the voucher number represented by the voucher code.
int voucherNumberPos = voucherCode.length() - 12;
String voucherNumberHex = voucherCode.substring(voucherNumberPos, voucherNumberPos + 6);
This is setting voucherNumberHex to a six-character long string, starting twelve from the end of voucherCode, in this case 93-E4D. It seems likely the author didn't expect the caller to include the hyphens when this code was first written. Even so the intent seems to be to ignore half the voucher code.
int firstByte = getIntFromHexByte(voucherNumberHex.substring(0, 2), 0);
int secondByte = getIntFromHexByte(voucherNumberHex.substring(2, 4), 1);
int thirdByte = getIntFromHexByte(voucherNumberHex.substring(4, 6), 7);
This looks straightforward at first, but the parameters 0, 1, and 7 are not offsets at all, despite the name of the argument. It's trying to turn each pair of hex digits into a byte, which would be sensible enough if not for the hyphen character. Now for the fun part:
private int getIntFromHexNibble(char value, int offset) {
int pos = getAlphabet().indexOf(value);
if (pos == -1) {// nothing found}
pos -= offset;
while (pos < 0) {
pos += 16;
}
return pos % 16;
}
The right curly brace after "found" is commented out, so the code you posted is actually incomplete. I'm going to assume there's another line or two that read
return pos;
}
So the basic idea is that M becomes 0, 9 becomes 1, and so on via the call to indexOf. But if this method sees a character not in the provided alphabet, like a hyphen, it uses the so-called offset to calculate a default value (in this case 14, if I've done the math in my head right), and returns that as the hex nibble value.
The end result is that you get back a number in the range 0 (inclusive) to 2^24 (exclusive). But of the 2^24 possible values such a number should have, only 2^20 different values will ever be returned. So from a voucher code that looks like twelve digits of base-32, which would have an astronomical number of values, you're limited to slightly over a million different voucher numbers within each customer prefix.
General advice:
Use peer reviews to prevent code like this from getting into
production.
Use unit tests to prove the code does what the function
name says it does.
Use exceptions to fail early if the input isn't
what you're expecting.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I found a code which will detect common elements in an unsorted array. The program runs in linear time! But i did not understand the logic of the program. It would be very helpful if some one could explain the logic of the program.
Here is the code:
public class DeleteUnsortedDataFromArray {
public static List<Integer> findDuplicatesArray(int[] sequence){
int bitarray = 0;
for(int i=0; i< sequence.length; i++){
int x = 1;
x = x << sequence[i];
if((bitarray & x) != 0){
System.out.println("Duplicate found in given array: " + sequence[i]);
} else {
bitarray = bitarray | x;
}
}
return null;
}
public static void main(String[] args) {
int[] input = {1,1,2,3};
findDuplicatesArray(input);
}
}
What it does is to represent each found value as an 1 in a position of the bits composing an integer (bitarray).
The lines:
x = 1;
x = x << sequence[i];
Will put a 1 at the position given by the sequence value+1 (<< is a shift operator).
For example, if sequence[i] value is four, x will have the binary value: ...010000
The line:
(bitarray & x) != 0
Uses bit operation AND to check if a position has been already occupied and hence the valued found.
The problem is that this algorithm only works if your values at sequence are constrained to be low: Between 0 and 30 as there are 32 bits in an Java integer and the value 0 is represented as a 1 at the position 0 of bitarray.
You should consider too what happens when the sequence values are negative.
It works only as long as all values in the array belong to [0, number-of-bits-in-int). If of course you can say 'works' about a function that is supposed to return list of duplicates but always returns null.
You can understand the algorithm as using an array of booleans to test whether a value has occured previously in the array or not. Now instead of using an array of booleans, what you are doing is using the bits in an int to represent whether a value has occured previously or not. The code calls this "bitarray".
To set the Ith bit in an int, you use
x = (x | (1<< i));
Here '|' is the bitwise or operator.
And to test whether the Ith bit has been set you check the condition
if((x & (1<< i)) != 0){
}
here '&' is the bitwise and operator.
Moreover, the algorithm used above will only work if the range of values in the array is between 0 and 31 inclusive. That's because java ints are represented using 32 bits. However it consumes lesser space than other alternatives like using a HashSet or an explicit array of booleans.
However, if space is at a premium, and you know that the range of data in the array is small, you can consider using Bitset class (link).
This question already has answers here:
How to get the separate digits of an int number?
(32 answers)
Closed 9 years ago.
I want to know how to extract digits from a number.
The only method I can think of is converting the number to a string, then use substring() - THEN convert back to int.
Would there be a more efficient way, such that it obtains a specific number like the substring() method, but for an int or a BigInteger?
To understand how to do it, consider this:
To remove all digits prior to digit k (counting from the back of the number), compute x % pow(10, k+1)
To truncate the last k digits of a number compute x / pow(10, k)
Now you can construct a method that removes the initial part and drops the ending part as needed to compute a substring. Note that the same trick can be applied to numeric representations other than decimal by substituting 10 with the base of the number (i.e. 2 for binary numbers, 16 for hex numbers, and so on).
If you are referring to extracting 1, 2, 3, 4 from 1234, you can use the modulo operator % as follows:
int i = 1234;
while (i > 0) {
System.out.println(i % 10);
i = i / 10;
}
this would print 4, 3, 2, 1. To get them in reverse order, you can use a stack to push the values and the pop them.
What you want to do is something like this:
int current = number;
do {
System.out.println((current % 10));
current = current / 10;
} while (currrent > 0);