How to convert binary to text in Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Binary to text in Java
I'm writing a program that can convert multiple things, but I need help with the converting of binary. I have my code for text-to-binary working, but I'm not sure about binary-to-text. Here is my code for the button which triggers the conversion:
String code = jTextArea5.getText();
if (code == null) {
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++){
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);
}
else
{
System.out.println(jTextArea1.getText( ));
String binary = jTextArea1.getText();
int ascii = Integer.parseInt(binary, 2);
char character = (char)ascii;
jTextArea5.setText("" + character);
}
If anyone knows how I can fix this code to work, that'd be great. Thanks!
NOTE - This bit below works on it's own, just not in conjunction with any efforts to allow converting binary in jTextArea5 to text in jTextArea1.
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++){
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);

Convert the binary into an integer:
String binary = "010101";
int ascii = Integer.parseInt(binary, 2);
Then turn the integer into ascii:
char character = (char)ascii;

Swap the 5 and the 1 around so it grabs the binary out of the correct textbox.
And use StringTokenizer to process each block of 8
Dont forget to import StringTokenizer
else
{
System.out.println(jTextArea5.getText( ));
String binary = jTextArea5.getText();
StringTokenizer st = new StringTokenizer(binary," ");
while(st.hasMoreTokens()){
int ascii = Integer.parseInt(st.nextToken(), 2);
char character = (char)ascii;
jTextArea1.setText(jTextArea1.getText() + "" + character);
}
}
this bit checks whats in jTextArea5.getText()
if (code == null) {
change it to
if (code.equals("")) {
and make sure you clear out whats in the text boxes before you start either conversion

Related

Converting a reversed Hexadecimal String to Decimal [duplicate]

This question already has answers here:
Converting some hexadecimal string to a decimal integer
(13 answers)
Closed 4 years ago.
I am currently writing a program that reads the ID of NFC Tags and reverses them. The thing I am trying to accomplish now is to convert that reversed ID from Hex to Dec
Let's say that the ID of the number would be "3bde4eac", so the reversed result would be "ac4edb3b"
And I don't really know how to correctly convert that HexString to Decimal.
Here is my current code:
else{
String tagInfo = tag.toString() + "\n";
tagInfo = "";
byte[] tagId = tag.getId();
for(int i=n; i<tagId.length; i++){
tagInfo += Integer.toHexString(tagId[i] & 0xFF);
}
String s = tagInfo;
StringBuilder result = new StringBuilder();
for(int n = 0; n <=s.length()-2; n=n+2) {
result.append(new StringBuilder(s.substring(n, n + 2)).reverse());
}
s = result.reverse().toString();
Long f = Long.parseLong(s, 16);
textViewInfo.setText(s);
}
EDIT: Using the "duplicate link", I was able to solve the problem.
I changed the last part of my code to
s = result.reverse().toString();
Long g = hex2decimal(s);
textViewInfo.setText(g.toString());
With the function
public static Long hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
long val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
long d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
You should try parsing the reversed string as hexadecimal and then convert the obtained int value to decimal. Check out Integer.parseInt(strValue, 16) to parse String in base16/hexadecimal and Integer.toString(intValue) for this.

Removing supplementary characters from a Java string [duplicate]

This question already has answers here:
What is the regex to extract all the emojis from a string?
(18 answers)
Closed 5 years ago.
I have a Java string that contains supplementary characters (characters in the Unicode standard whose code points are above U+FFFF). These characters could for example be emojis. I want to remove those characters from the string, i.e. replace them with the empty string "".
How do I remove supplementary characters from a string?
How do I remove characters from an arbitrary code point range? (For example all characters in the range 1F000–​1FFFF)?
There are a couple of approaches. As regex replace is expensive, maybe do:
String basic(String s) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
if (!Character.isLowSurrogate(ch) && !Character.isHighSurrogate(ch)) {
sb.append(ch);
}
}
return sb.length() == s.length() ? s : sb.toString();
}
You can get a character's unicode value by simply converting it to an int.
Therefore, you'll want to do the following:
Convert your String to a char[], or do something like have the loop condition iterate through each character in the String using String.charAt()
Check if the unicode value is one you want to remove.
If so, replace the character with "".
This is just to start you off, however if you're still struggling I can try type out a whole example.
Good luck!
Here is a code snippet that collects characters between code point 60 and 100:
public class Test {
public static void main(String[] args) {
new Test().go();
}
private void go() {
String s = "ABC12三○";
String ret = "";
for (int i = 0; i < s.length(); i++) {
System.out.println(s.codePointAt(i));
if ((s.codePointAt(i) > 60) & (s.codePointAt(i) < 100)) {
ret += s.substring(i, i+1);
}
}
System.out.println(ret);
}
}
the result:
code point: 65
code point: 66
code point: 67
code point: 49
code point: 50
code point: 19977
code point: 65518
result: ABC
Hope this helps.
Java strings are UTF-16 encoded. The String type has a codePointAt() method for retrieving a decoded codepoint at a given char (codeunit) index.
So, you can do something like this, for instance:
String removeSupplementaryChars(String s)
{
int len = s.length();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(len);
int i = 0;
do
{
if (s.codePointAt(i) <= 0xFFFF)
sb.append(s.charAt[i]);
i = s.offsetByCodePoints(i, 1);
}
while (i < len);
return sb.toString();
}
Or this:
String removeCodepointsinRange(String s, int lower, int upper)
{
int len = s.length();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(len);
int i = 0;
do
{
int cp = s.codePointAt(i);
if ((cp < lower) || (cp > upper))
sb.appendCodePoint(cp);
i = s.offsetByCodePoints(i, 1);
}
while (i < len);
return sb.toString();
}

How to convert (English) String to binary form using java?

I have a text file, which is divided in 3 part, and now I want to convert this divided block to binary format and store in database.
Please help me to solve this problem.
Thanks.
String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;
and I need firstblock in binary form.
String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;
byte[] bytes = firstblock.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println(binary);
and you can check it binary to string
Use getBytes() method.
See the below
String text = "Hello World!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Update:
Try with below code:
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
Reference :
Convert A String (like testing123) To Binary In Java
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
you try with this code if you want to use online tool
An English to binary translator is a tool that can convert text
written in the English language into a sequence of 0s and 1s, which is
known as binary code. This is the language that computers understand
and use to process and store data.
Here is an example of how it would work:
Input: "Hello" Output: "01001000 01100101 01101100 01101100 01101111"
The translator would take the word "Hello" and convert each letter
into its corresponding 8-bit binary code representation.

How store hexadecimal strings in a Byte array? [duplicate]

I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.
I couldn't have phrased it better than the person that posted the same question here.
But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the
byte[] {0x00,0xA0,0xBf}
what should I do?
I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.
Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years):
HexFormat.of().parseHex(s)
For older versions of Java:
Here's a solution that I think is better than any posted so far:
/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Reasons why it is an improvement:
Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)
Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte.
No library dependencies that may not be available
Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.
One-liners:
import javax.xml.bind.DatatypeConverter;
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
Warnings:
in Java 9 Jigsaw this is no longer part of the (default) java.se root
set so it will result in a ClassNotFoundException unless you specify
--add-modules java.se.ee (thanks to #eckes)
Not available on Android (thanks to Fabian for noting that), but you can just take the source code if your system lacks javax.xml for some reason. Thanks to #Bert Regelink for extracting the source.
The Hex class in commons-codec should do that for you.
http://commons.apache.org/codec/
import org.apache.commons.codec.binary.Hex;
...
byte[] decoded = Hex.decodeHex("00A0BF");
// 0x00 0xA0 0xBF
You can now use BaseEncoding in guava to accomplish this.
BaseEncoding.base16().decode(string);
To reverse it use
BaseEncoding.base16().encode(bytes);
Actually, I think the BigInteger is solution is very nice:
new BigInteger("00A0BF", 16).toByteArray();
Edit: Not safe for leading zeros, as noted by the poster.
One-liners:
import javax.xml.bind.DatatypeConverter;
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
For those of you interested in the actual code behind the One-liners from FractalizeR (I needed that since javax.xml.bind is not available for Android (by default)), this comes from com.sun.xml.internal.bind.DatatypeConverterImpl.java :
public byte[] parseHexBinary(String s) {
final int len = s.length();
// "111" is not a valid hex encoding.
if( len%2 != 0 )
throw new IllegalArgumentException("hexBinary needs to be even-length: "+s);
byte[] out = new byte[len/2];
for( int i=0; i<len; i+=2 ) {
int h = hexToBin(s.charAt(i ));
int l = hexToBin(s.charAt(i+1));
if( h==-1 || l==-1 )
throw new IllegalArgumentException("contains illegal character for hexBinary: "+s);
out[i/2] = (byte)(h*16+l);
}
return out;
}
private static int hexToBin( char ch ) {
if( '0'<=ch && ch<='9' ) return ch-'0';
if( 'A'<=ch && ch<='F' ) return ch-'A'+10;
if( 'a'<=ch && ch<='f' ) return ch-'a'+10;
return -1;
}
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
public String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length*2);
for ( byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
The HexBinaryAdapter provides the ability to marshal and unmarshal between String and byte[].
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
public byte[] hexToBytes(String hexString) {
HexBinaryAdapter adapter = new HexBinaryAdapter();
byte[] bytes = adapter.unmarshal(hexString);
return bytes;
}
That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it.
Here is a method that actually works (based on several previous semi-correct answers):
private static byte[] fromHexString(final String encoded) {
if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input string must contain an even number of characters");
final byte result[] = new byte[encoded.length()/2];
final char enc[] = encoded.toCharArray();
for (int i = 0; i < enc.length; i += 2) {
StringBuilder curr = new StringBuilder(2);
curr.append(enc[i]).append(enc[i + 1]);
result[i/2] = (byte) Integer.parseInt(curr.toString(), 16);
}
return result;
}
The only possible issue that I can see is if the input string is extremely long; calling toCharArray() makes a copy of the string's internal array.
EDIT: Oh, and by the way, bytes are signed in Java, so your input string converts to [0, -96, -65] instead of [0, 160, 191]. But you probably knew that already.
In android ,if you are working with hex, you can try okio.
simple usage:
byte[] bytes = ByteString.decodeHex("c000060000").toByteArray();
and result will be
[-64, 0, 6, 0, 0]
The BigInteger() Method from java.math is very Slow and not recommandable.
Integer.parseInt(HEXString, 16)
can cause problems with some characters without
converting to Digit / Integer
a Well Working method:
Integer.decode("0xXX") .byteValue()
Function:
public static byte[] HexStringToByteArray(String s) {
byte data[] = new byte[s.length()/2];
for(int i=0;i < s.length();i+=2) {
data[i/2] = (Integer.decode("0x"+s.charAt(i)+s.charAt(i+1))).byteValue();
}
return data;
}
Have Fun, Good Luck
EDIT: as pointed out by #mmyers, this method doesn't work on input that contains substrings corresponding to bytes with the high bit set ("80" - "FF"). The explanation is at Bug ID: 6259307 Byte.parseByte not working as advertised in the SDK Documentation.
public static final byte[] fromHexString(final String s) {
byte[] arr = new byte[s.length()/2];
for ( int start = 0; start < s.length(); start += 2 )
{
String thisByte = s.substring(start, start+2);
arr[start/2] = Byte.parseByte(thisByte, 16);
}
return arr;
}
For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation.
public static byte[] hexStringToByteArray(String input) {
int len = input.length();
if (len == 0) {
return new byte[] {};
}
byte[] data;
int startIdx;
if (len % 2 != 0) {
data = new byte[(len / 2) + 1];
data[0] = (byte) Character.digit(input.charAt(0), 16);
startIdx = 1;
} else {
data = new byte[len / 2];
startIdx = 0;
}
for (int i = startIdx; i < len; i += 2) {
data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
+ Character.digit(input.charAt(i+1), 16));
}
return data;
}
I like the Character.digit solution, but here is how I solved it
public byte[] hex2ByteArray( String hexString ) {
String hexVal = "0123456789ABCDEF";
byte[] out = new byte[hexString.length() / 2];
int n = hexString.length();
for( int i = 0; i < n; i += 2 ) {
//make a bit representation in an int of the hex value
int hn = hexVal.indexOf( hexString.charAt( i ) );
int ln = hexVal.indexOf( hexString.charAt( i + 1 ) );
//now just shift the high order nibble and add them together
out[i/2] = (byte)( ( hn << 4 ) | ln );
}
return out;
}
I've always used a method like
public static final byte[] fromHexString(final String s) {
String[] v = s.split(" ");
byte[] arr = new byte[v.length];
int i = 0;
for(String val: v) {
arr[i++] = Integer.decode("0x" + val).byteValue();
}
return arr;
}
this method splits on space delimited hex values but it wouldn't be hard to make it split the string on any other criteria such as into groupings of two characters.
The Code presented by Bert Regelink simply does not work.
Try the following:
import javax.xml.bind.DatatypeConverter;
import java.io.*;
public class Test
{
#Test
public void testObjectStreams( ) throws IOException, ClassNotFoundException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
String stringTest = "TEST";
oos.writeObject( stringTest );
oos.close();
baos.close();
byte[] bytes = baos.toByteArray();
String hexString = DatatypeConverter.printHexBinary( bytes);
byte[] reconvertedBytes = DatatypeConverter.parseHexBinary(hexString);
assertArrayEquals( bytes, reconvertedBytes );
ByteArrayInputStream bais = new ByteArrayInputStream(reconvertedBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
String readString = (String) ois.readObject();
assertEquals( stringTest, readString);
}
}
I found Kernel Panic to have the solution most useful to me, but ran into problems if the hex string was an odd number. solved it this way:
boolean isOdd(int value)
{
return (value & 0x01) !=0;
}
private int hexToByte(byte[] out, int value)
{
String hexVal = "0123456789ABCDEF";
String hexValL = "0123456789abcdef";
String st = Integer.toHexString(value);
int len = st.length();
if (isOdd(len))
{
len+=1; // need length to be an even number.
st = ("0" + st); // make it an even number of chars
}
out[0]=(byte)(len/2);
for (int i =0;i<len;i+=2)
{
int hh = hexVal.indexOf(st.charAt(i));
if (hh == -1) hh = hexValL.indexOf(st.charAt(i));
int lh = hexVal.indexOf(st.charAt(i+1));
if (lh == -1) lh = hexValL.indexOf(st.charAt(i+1));
out[(i/2)+1] = (byte)((hh << 4)|lh);
}
return (len/2)+1;
}
I am adding a number of hex numbers to an array, so i pass the reference to the array I am using, and the int I need converted and returning the relative position of the next hex number. So the final byte array has [0] number of hex pairs, [1...] hex pairs, then the number of pairs...
Based on the op voted solution, the following should be a bit more efficient:
public static byte [] hexStringToByteArray (final String s) {
if (s == null || (s.length () % 2) == 1)
throw new IllegalArgumentException ();
final char [] chars = s.toCharArray ();
final int len = chars.length;
final byte [] data = new byte [len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));
}
return data;
}
Because: the initial conversion to a char array spares the length checks in charAt
If you have a preference for Java 8 streams as your coding style then this can be achieved using just JDK primitives.
String hex = "0001027f80fdfeff";
byte[] converted = IntStream.range(0, hex.length() / 2)
.map(i -> Character.digit(hex.charAt(i * 2), 16) << 4 | Character.digit(hex.charAt((i * 2) + 1), 16))
.collect(ByteArrayOutputStream::new,
ByteArrayOutputStream::write,
(s1, s2) -> s1.write(s2.toByteArray(), 0, s2.size()))
.toByteArray();
The , 0, s2.size() parameters in the collector concatenate function can be omitted if you don't mind catching IOException.
If your needs are more than just the occasional conversion then you can use HexUtils.
Example:
byte[] byteArray = Hex.hexStrToBytes("00A0BF");
This is the most simple case. Your input may contain delimiters (think MAC addresses, certificate thumbprints, etc), your input may be streaming, etc. In such cases it gets easier to justify to pull in an external library like HexUtils, however small.
With JDK 17 the HexFormat class will fulfill most needs and the need for something like HexUtils is greatly diminished. However, HexUtils can still be used for things like converting very large amounts to/from hex (streaming) or pretty printing hex (think wire dumps) which the JDK HexFormat class cannot do.
(full disclosure: I'm the author of HexUtils)
public static byte[] hex2ba(String sHex) throws Hex2baException {
if (1==sHex.length()%2) {
throw(new Hex2baException("Hex string need even number of chars"));
}
byte[] ba = new byte[sHex.length()/2];
for (int i=0;i<sHex.length()/2;i++) {
ba[i] = (Integer.decode(
"0x"+sHex.substring(i*2, (i+1)*2))).byteValue();
}
return ba;
}
My formal solution:
/**
* Decodes a hexadecimally encoded binary string.
* <p>
* Note that this function does <em>NOT</em> convert a hexadecimal number to a
* binary number.
*
* #param hex Hexadecimal representation of data.
* #return The byte[] representation of the given data.
* #throws NumberFormatException If the hexadecimal input string is of odd
* length or invalid hexadecimal string.
*/
public static byte[] hex2bin(String hex) throws NumberFormatException {
if (hex.length() % 2 > 0) {
throw new NumberFormatException("Hexadecimal input string must have an even length.");
}
byte[] r = new byte[hex.length() / 2];
for (int i = hex.length(); i > 0;) {
r[i / 2 - 1] = (byte) (digit(hex.charAt(--i)) | (digit(hex.charAt(--i)) << 4));
}
return r;
}
private static int digit(char ch) {
int r = Character.digit(ch, 16);
if (r < 0) {
throw new NumberFormatException("Invalid hexadecimal string: " + ch);
}
return r;
}
Is like the PHP hex2bin() Function but in Java style.
Example:
String data = new String(hex2bin("6578616d706c65206865782064617461"));
// data value: "example hex data"
Late to the party, but I have amalgamated the answer above by DaveL into a class with the reverse action - just in case it helps.
public final class HexString {
private static final char[] digits = "0123456789ABCDEF".toCharArray();
private HexString() {}
public static final String fromBytes(final byte[] bytes) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
buf.append(HexString.digits[(bytes[i] >> 4) & 0x0f]);
buf.append(HexString.digits[bytes[i] & 0x0f]);
}
return buf.toString();
}
public static final byte[] toByteArray(final String hexString) {
if ((hexString.length() % 2) != 0) {
throw new IllegalArgumentException("Input string must contain an even number of characters");
}
final int len = hexString.length();
final byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
And JUnit test class:
public class TestHexString {
#Test
public void test() {
String[] tests = {"0FA1056D73", "", "00", "0123456789ABCDEF", "FFFFFFFF"};
for (int i = 0; i < tests.length; i++) {
String in = tests[i];
byte[] bytes = HexString.toByteArray(in);
String out = HexString.fromBytes(bytes);
System.out.println(in); //DEBUG
System.out.println(out); //DEBUG
Assert.assertEquals(in, out);
}
}
}
I know this is a very old thread, but still like to add my penny worth.
If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.
public static byte[] hexToBinary(String s){
/*
* skipped any input validation code
*/
byte[] data = new byte[s.length()/2];
for( int i=0, j=0;
i<s.length() && j<data.length;
i+=2, j++)
{
data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);
}
return data;
}
I think will do it for you. I cobbled it together from a similar function that returned the data as a string:
private static byte[] decode(String encoded) {
byte result[] = new byte[encoded/2];
char enc[] = encoded.toUpperCase().toCharArray();
StringBuffer curr;
for (int i = 0; i < enc.length; i += 2) {
curr = new StringBuffer("");
curr.append(String.valueOf(enc[i]));
curr.append(String.valueOf(enc[i + 1]));
result[i] = (byte) Integer.parseInt(curr.toString(), 16);
}
return result;
}
For Me this was the solution, HEX="FF01" then split to FF(255) and 01(01)
private static byte[] BytesEncode(String encoded) {
//System.out.println(encoded.length());
byte result[] = new byte[encoded.length() / 2];
char enc[] = encoded.toUpperCase().toCharArray();
String curr = "";
for (int i = 0; i < encoded.length(); i=i+2) {
curr = encoded.substring(i,i+2);
System.out.println(curr);
if(i==0){
result[i]=((byte) Integer.parseInt(curr, 16));
}else{
result[i/2]=((byte) Integer.parseInt(curr, 16));
}
}
return result;
}

write raw binary to file java

Say I have a binary string ("0 and 1s") and I want to write this string to a binary file, how can this be done in java? I tried converting to ASCII values string, then create a ByteArrayInputStream from that but values over 127 do not display correctly. Can anyone help me with this?
My binaryToAscii method:
public static String BinaryToAscii(String bin){
int num_of_bytes = bin.length()/8;
StringBuilder sb = new StringBuilder();
int index = 0;
String byte_code;
Character char_code;
for (int i =0; i<num_of_bytes;i++){
index = i*8;
byte_code = bin.substring(index,index+8);
int charCode = Integer.parseInt(byte_code, 2);
char_code = new Character((char)charCode);
sb.append(char_code);
}
return sb.toString();
}
Then I convert the returned string to a ByteArrayInputStream using
InputStream is = new ByteArrayInputStream(ascii.toString().getBytes());
you first would transform the 0 / 1 string to a byte[].
then write out using
DataOutputStream.writeByte().
read in with
DataInputStream.readUnsignedByte() // to get 0 - 255
To convert string to binary use this:
You will first need to break the string into its individual letters then run them through this one at a time.
char letter = c;
byte[] bytes = letter.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println(binary);

Categories