Java Hex number increase by one - java

I have some auto generated ids represented as a HEX String. I want to find the next 1000 values. For instance, let's suppose I have the following string
String keyFrom = "536a11dae4b062cab536549d";
How can I get from a java code the following, into String?
536a11dae4b062cab536549e
536a11dae4b062cab536549f
536a11dae4b062cab53654a0
536a11dae4b062cab53654a1
536a11dae4b062cab53654a2 ... etc.

Use BigInteger as below
BigInteger decimal = new BigInteger("536a11dae4b062cab536549d",16);
for ( int i=0;i<1000;i++){
decimal = decimal.add(BigInteger.ONE);
System.out.println(decimal.toString(16));
}

Convert your String to BigInteger and increment it:
BigInteger bigInt = new BigInteger(hexString, 16);
for(int i = 0 ; i < 1000 ; ++i) {
// do something with bigInt...
System.out.println(bigInt.toString(16));
bigInt = bigInt.add(BigInteger.ONE);
}

EDIT: If your using hex strings longer than ~8 characters, use the solution using BigInteger above.
Use Integer#parseInt(String, 16) to parse the hex string into an integer, add one to it, and then use Integer#toHexString to turn it back to hexadecimal.
String hexString = "A953CF";
// 16 sepcifies the string to be in base 16, hexadecimal
int hexAsInt = Integer.parseInt(hexString, 16);
hexAsInt += 6; // Add 6
String newHexString = Integer.toHexString(hexAsInt);
System.out.println(newHexString);
--> A953D4
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toHexString(int)

Related

Convert hex string value to hex int

How can I convert the hexstring into the form of hexint below?
string hexstring = "0x67";
int hexint = 0x67;
Integer#decode can be used to convert hexadecmial string representation into its integer value:
Integer.decode("0x67");
This function automatically detects the correct base and will parse return the int 103 (0x67 = 6*16+7). If you want to manually specify a different base, see my other answer
If you only have a single byte, you can strip of the leading "0x" part and then parse as a base-16 number with Integer#parseInt:
Integer.parseInt("0x67".substring(2), 0x10);
Integer.parseInt("0x67".substring(2), 16);
0x10 is the hexadecimal representation of the decimal number 16.
String hexstring = "67";
int hexint = Integer.parseInt(hexstring, 16);
System.out.println(hexint); // 103 (decimal)
With Integer.parseInt(String s, int radix) you can parse a String to an int.
The radix is the base of that number system, in case of hex-values it is 16.

Java - Hex String representation to integer Hex

I have a string as "5F2A" as Hex. I would like to convert it as int 0x5F2A.
String str = "5F2A";
int number = someOperation(str);
And the number should be (with 0x)
0x5F2A
Is it possible?
To rephrase and share what I learnt today
Map<Integer, String> map = new HashMap<>();
map.put(0x5F2A, "somevalue");
System.out.println(map.get(24362));
System.out.println(map.get(0b0101111100101010));
Would give the value somevalue for both.
No transformation required:
System.out.println("0x" + str);
And to turn an arbitrary int into HEX representation:
Integer.toHexString(intNumber);
That should be all you need to get going!
int i = 0x5F2A not really means nothing because in memory, all is in binary, it's only when you print that it matters
String str = "5F2A";
int number = Integer.parseInt(str, 16); //alows to store an int, binary 0101111100101010
System.out.println(number); //24362 (decimal by default)
System.out.println(Integer.toHexString(number)); //5f2a (hexa possible too)
By default, it prints in (binary into) decimal format, but you can print in hexa format, but int i = 0x5F2A means at 100% the same as int i = 24362
See here
Integer.parseInt(/*your String*/, 16);
16 is the radix for hexadecimal.

How to convert binary string to Java String encoded using UFT-8

In order to send a chunk of bits from a 4 words String, I'm doing getting the byte array from the String and calculating the bit string.
StringBuilder binaryStr = new StringBuilder();
byte[] bytesFromStr = str.getBytes("UTF-8");
for (int i = 0, l = bytesFromStr.length; i < l; i++) {
binaryStr.append(Integer.toBinaryString(bytesFromStr[i]));
}
String result = binaryStr.toString();
The problem appears when I want to do the reverse operation: converting a bit string to a Java String encoded using UTF-8.
Please, Is there someone that can explain me the best way to do that?
Thanks in advance!
TL;DR Don't use toBinaryString(). See solution at the end.
Your problem is that Integer.toBinaryString() doesn't return leading zeroes, e.g.
System.out.println(Integer.toBinaryString(1)); // prints: 1
System.out.println(Integer.toBinaryString(10)); // prints: 1010
System.out.println(Integer.toBinaryString(100)); // prints: 1100100
For your purpose, you want to always get 8 bits for each byte.
You also need to prevent negative values from causing errors, e.g.
System.out.println(Integer.toBinaryString((byte)129)); // prints: 11111111111111111111111110000001
Easiest way to accomplish that is like this:
Integer.toBinaryString((b & 0xFF) | 0x100).substring(1)
First, it coerces the byte b to int, then retains only lower 8 bits, and finally sets the 9th bit, e.g. 129 (decimal) becomes 1 1000 0001 (binary, spaces added for clarity). It then excludes that 9th bit, in effect ensuring that leading zeroes are in place.
It's better to have that as a helper method:
private static String toBinary(byte b) {
return Integer.toBinaryString((b & 0xFF) | 0x100).substring(1);
}
In which case your code becomes:
StringBuilder binaryStr = new StringBuilder();
for (byte b : str.getBytes("UTF-8"))
binaryStr.append(toBinary(b));
String result = binaryStr.toString();
E.g. if str = "Hello World", you get:
0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100
You could of course just do it yourself, without resorting to toBinaryString():
StringBuilder binaryStr = new StringBuilder();
for (byte b : str.getBytes("UTF-8"))
for (int i = 7; i >= 0; i--)
binaryStr.append((b >> i) & 1);
String result = binaryStr.toString();
That will probably run faster too.
Thanks #Andreas for your code. I test using your function and "decoding" again to UTF-8 using this:
StringBuilder revealStr = new StringBuilder();
for (int i = 0; i < result.length(); i += 8) {
revealStr.append((char) Integer.parseUnsignedInt(result.substring(i, i + 8), 2));
}
Thanks for all folks to help me.

java - Enforce 4 digit hex representation of a binary number

Below is a snippet of my java code.
//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
BigInteger temp = new BigInteger(binaryNumber, 2);
return temp.toString(16).toUpperCase();
}
If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits?
Thanks.
You do one of the following:
Manually pad with zeroes
Use String.format()
Manually pad with zeroes
Since you want extra leading zeroes when shorter than 4 digits, use this:
BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
hex = "000".substring(hex.length() - 1) + hex;
return hex;
Use String.format()
BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);
Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger.
In Java 8, do it by parsing the binary input as an unsigned number:
int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);
The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.
I customized your code a bit to include leading zeros based on input string:
public static void main(String[] args) {
System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
BigInteger temp = new BigInteger(binaryNumber, 2);
String hexStr = temp.toString(16).toUpperCase();
int b16inLen = binaryNumber.length()/4;
int b16outLen = hexStr.length();
int b16padding = b16inLen - b16outLen;
for (int i=0; i<b16padding; i++) {
hexStr=('0'+hexStr);
}
return hexStr;
}
Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.

Converting String type binary number to bit in java

I have a question about converting String type binary number to bit and write in the txt file.
For example we have String like "0101011" and want to convert to bit type "0101011"
then write in to the file on the disk.
I would like to know is there anyway to covert to string to bit..
i was searching on the web they suggest to use bitarray but i am not sure
thanks
Try this:
int value = Integer.parseInt("0101011", 2); // parse base 2
Then the bit pattern in value will correspond to the binary interpretation of the string "0101011". You can then write value out to a file as a byte (assuming the string is no more than 8 binary digits).
EDIT You could also use Byte.parseByte("0101011", 2);. However, byte values in Java are always signed. If you tried to parse an 8-bit value with the 8th bit set (like "10010110", which is 150 decimal), you would get a NumberFormatException because values above +127 do not fit in a byte. If you don't need to handle bit patterns greater than "01111111", then Byte.parseByte works just as well as Integer.parseInt.
Recall, though, that to write a byte to a file, you use OutputStream.write(int), which takes an int (not byte) value—even though it only writes one byte. Might as well go with an int value to start with.
You can try the below code to avoid overflows of the numbers.
long avoidOverflows = Long.parseLong("11000000000000000000000000000000", 2);
int thisShouldBeANegativeNumber = (int) avoidOverflows;
System.out.println("Currect value : " + avoidOverflows + " -> " + "Int value : " + thisShouldBeANegativeNumber);
you can see the output
Currect value : 3221225472 -> Int value : -1073741824
//Converting String to Bytes
bytes[] cipherText= new String("0101011").getBytes()
//Converting bytes to Bits and Convert to String
StringBuilder sb = new StringBuilder(cipherText.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * cipherText .length; i++ )
sb.append((cipherText [i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
//Byte code of input in Stirn form
System.out.println("Bytecode="+sb.toString()); // some binary data
//Convert Byte To characters
String bin = sb.toString();
StringBuilder b = new StringBuilder();
int len = bin.length();
int i = 0;
while (i + 8 <= len) {
char c = convert(bin.substring(i, i+8));
i+=8;
b.append(c);
}
//String format of Binary data
System.out.println(b.toString());

Categories