I`m working on a project and I had to convert a hex String to a binary String I used a lot of methods but the code below was the most useful to me although this code creates an unknown hex number "l" which looks like 1 but is not one, does some one know what this thing is(l)? and how did it appear and how to fix it and convert it to "1" ?
public String hexToBin(String hex){
String bin =new String();
String binFragment =new String();
int iHex;
hex = hex.trim();
hex = hex.replaceFirst("0x","");
for(int i = 0; i < hex.length(); i++){
iHex = Integer.parseInt(""+hex.charAt(i),16);
binFragment = Integer.toBinaryString(iHex);
while(binFragment.length() < 4){
binFragment = "0" + binFragment;
}
bin += binFragment;
}
You should use Integer.decode() instead of Integer.parseInt() as it handles hex strings as well.
See; http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#decode(java.lang.String)
Use BigInteger.toString(radix). The radix being what base you want to use. So with binary, also known as base2, fill in 2.
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}
Related
I am trying to make a function that turns a binary number into letters according to the positions of the one's inside of it.
For example if i had the binary number : 0101
I want to take the String "LUDR" and effectively multiply them together to get
: "UR".
I have the 4 bit binary numbers in an array and the string that i want to 'multiply' them with is always going to be "LUDR".
I will give more examples..
binary number of : 1011 gives "LDR"
binary number of : 0001 gives "R"
EDIT:
the code i have already written :
String[][] binVals = new String[10][10];
//my function to fill up with 4 bit binary values so i can get 100 in total
//just read from file so that's why it's a string array
String mazeWallRemove = "LURD";
//I need to write some function to turn the binary values in to some string
String[][] unCodedWalls = new String[10][10]//into this array
my question is what functions can i use to 'multiply' the binVals and the "LURD" string to get the string output(in the form as shown above)
I can just write 15 if statments converting each binary value from the array into an integer and then just saying:
for(int a = 0; a < 10; a++){
for(int b = 0; b < 10; b++){
if(binVals[a][b] == 1){
uncodedWalls[a][b] = "R"
} // lots more else if statements
}
}
this method is horribly inefficient and so i'm looking for a more efficient way to do it instead of making tons of if statements.
You can use the charAt method available in String class to construct the string you need. Pass the binary number and string you want to multiply to this method. This will check the character in the binary String is 1 and get the corresponding value from the original String and append it.
public String multiply(String value, String binary) {
String finalString = "";
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
finalString+=value.charAt(i);
}
}
return finalString;
}
I am in need to mask PII data for my application. The PII data will be of String format and of variable lengths, as it may include name, address, mail id's etc.
So i need to mask these data before logging them, it should not be a full mask instead, if the length of string is less than or equal to 8 characters then mask the first half with "XXX etc.."
If the length is more than 8 then mask the first and last portion of the string such that only the mid 5 characters are visible.
I know we can do this using java sub-stringa nd iterating over the string, but want to know if there is any other simple solution to address this.
Thanks in advance
If you are using Apache Commons, you can do like
String maskChar = "*";
//number of characters to be masked
String maskString = StringUtils.repeat( maskChar, 4);
//string to be masked
String str = "FirstName";
//this will mask first 4 characters of the string
System.out.println( StringUtils.overlay(str, maskString, 0, 4) );
You can check the string length before generating maskString using if else statement.
You can use this function; change the logic of half's as per your needs:
public static String maskedVariableString(String original)
{
String maskedString = null;
if(original.length()<9)
{
int half = original.length()/2;
StringBuilder sb =new StringBuilder("");
for(int i=0;i<(original.length()-half);i++)
{
sb.append("X");
}
maskedString = original.replaceAll("\\b.*(\\d{"+half+"})", sb.toString()+"$1");
}
else
{
int maskLength = original.length()-5;
int firstMaskLength = maskLength/2;
int secondMaskLength = maskLength-firstMaskLength;
StringBuilder sb =new StringBuilder("");
for(int i=0;i<firstMaskLength;i++)
{
sb.append("X");
}
String firstMask = sb.toString();
StringBuilder sb1 =new StringBuilder("");
for(int i=0;i<secondMaskLength;i++)
{
sb1.append("X");
}
String secondMask = sb1.toString();
maskedString = original.replaceAll("\\b(\\d{"+firstMaskLength+"})(\\d{5})(\\d{"+secondMaskLength+"})", firstMask+"$2"+secondMask);
}
return maskedString;
}
Explanation:
() groups the regular expression and we can use $ to access this group($1, $2,$3).
The \b boundary helps check that we are the start of the digits (there are other ways to do this, but here this will do).
(\d{+half+}) captures (half) no of digits to Group 1. The same happens in the else part also.
Considering the following String
String hexData = "1E01";
Is there a simple implementation to turn any hexData into a bit-based String array, like
String hexDataBits = "0001111000000001";
?
Here you go. Convert your hex string to an int value using the built in parseInt function, then turn that into a binary string.
public String hexToBinary(String hexBits) {
int intversion = Integer.parseInt(hexBits, 16);
String binaryVers = Integer.toBinaryString(intversion);
return binaryVers;
}
Note that this is not padded. If you want to pad it, modify binaryVers.
eg:
// if you're dead set on having at least 16 chars, put this before the return statement
int padding = 16 - binaryVers.length();
while (padding > 0) {
binaryVers = "0" + binaryVers;
padding--;
}
I would like to turn all values into the following number format, x.xxx. I am doing this fine by using a while loop and concatenating 0 to string values that do not have the correct length. However, I would like to know if there is a more efficient way of doing this. To be more clear of what I am trying to do, here are some examples.
Ex1--Change a string value such as 2.5 to 2.500
Ex2--Change a string value such as 2.51 to 2.510.
This is how I am currently doing this.
while (str.length() < 5) {
str= str+ "0";
}
You can use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(2.5));
Wow,that was an amazing one Reimeus!
Anywy,how is this ? :P
int totalLenght = str.length();
if(totalLenght>5){
str = str.substring(0,5);
}else{
int remLength = 5 - totalLenght;
for(int i=0;i<remLength;i++){
str = str +"0";
}
}
I have sort of a funky question (that I hope hasn't been asked and answered yet). To start, I'll tell you the order of what I'm trying to do and how I'm doing it and then tell you where I'm having a problem:
Convert a string of characters into ASCII numbers
Convert those ASCII numbers into binary and store them in a string
Convert those binary numbers back into ASCII numbers
Convert the ASCII numbers back into normal characters
Here are the methods I've written so far:
public static String strToBinary(String inputString){
int[] ASCIIHolder = new int[inputString.length()];
//Storing ASCII representation of characters in array of ints
for(int index = 0; index < inputString.length(); index++){
ASCIIHolder[index] = (int)inputString.charAt(index);
}
StringBuffer binaryStringBuffer = new StringBuffer();
/* Now appending values of ASCIIHolder to binaryStringBuffer using
* Integer.toBinaryString in a for loop. Should not get an out of bounds
* exception because more than 1 element will be added to StringBuffer
* each iteration.
*/
for(int index =0;index <inputString.length();index ++){
binaryStringBuffer.append(Integer.toBinaryString
(ASCIIHolder[index]));
}
String binaryToBeReturned = binaryStringBuffer.toString();
binaryToBeReturned.replace(" ", "");
return binaryToBeReturned;
}
public static String binaryToString(String binaryString){
int charCode = Integer.parseInt(binaryString, 2);
String returnString = new Character((char)charCode).toString();
return returnString;
}
I'm getting a NumberFormatException when I run the code and I think it's because the program is trying to convert the binary digits as one entire binary number rather than as separate letters. Based on what you see here, is there a better way to do this overall and/or how can I tell the computer to recognize the ASCII characters when it's iterating through the binary code? Hope that's clear and if not I'll be checking for comments.
So I used OP's code with some modifications and it works really well for me.
I'll post it here for future people. I don't think OP needs it anymore because he probably figured it out in the past 2 years.
public class Convert
{
public String strToBinary(String inputString){
int[] ASCIIHolder = new int[inputString.length()];
//Storing ASCII representation of characters in array of ints
for(int index = 0; index < inputString.length(); index++){
ASCIIHolder[index] = (int)inputString.charAt(index);
}
StringBuffer binaryStringBuffer = new StringBuffer();
/* Now appending values of ASCIIHolder to binaryStringBuffer using
* Integer.toBinaryString in a for loop. Should not get an out of bounds
* exception because more than 1 element will be added to StringBuffer
* each iteration.
*/
for(int index =0;index <inputString.length();index ++){
binaryStringBuffer.append(Integer.toBinaryString
(ASCIIHolder[index]));
}
String binaryToBeReturned = binaryStringBuffer.toString();
binaryToBeReturned.replace(" ", "");
return binaryToBeReturned;
}
public String binaryToString(String binaryString){
String returnString = "";
int charCode;
for(int i = 0; i < binaryString.length(); i+=7)
{
charCode = Integer.parseInt(binaryString.substring(i, i+7), 2);
String returnChar = new Character((char)charCode).toString();
returnString += returnChar;
}
return returnString;
}
}
I'd like to thank OP for writing most of it out for me. Fixing errors is much easier than writing new code.
You've got at least two problems here:
You're just concatenating the binary strings, with no separators. So if you had "1100" and then "0011" you'd get "11000011" which is the same result as if you had "1" followed by "1000011".
You're calling String.replace and ignoring the return result. This sort of doesn't matter as you're replacing spaces, and there won't be any spaces anyway... but there should be!
Of course you don't have to use separators - but if you don't, you need to make sure that you include all 16 bits of each UTF-16 code point. (Or validate that your string only uses a limited range of characters and go down to an appropriate number of bits, e.g. 8 bits for ISO-8859-1 or 7 bits for ASCII.)
(I have to wonder what the point of all of this is. Homework? I can't see this being useful in real life.)