How can I convert a binary string to a byte? - java

I'm working on Huffman compression.
String binaryString = "01011110";
outFile.write(byte);
I have a String which I want to convert to a byte so that I can write that byte to the file. Does anyone know how I can do this?

You can turn that String into a numerical value using the overloaded parseByte that lets you specify the radix:
String binaryString = "01011110";
byte b = Byte.parseByte(binaryString, 2); //this parses the string as a binary number
outFile.write(b);
The second argument to parseByte() lets you specify the Number system in which the String should be parsed. By default, a radix of 10 is used because us humans usually use the decimal system. The 2 says that the number should be treated as a binary value (which is base 2).

You can use Byte.parseByte() with a radix of 2:
byte b = Byte.parseByte(str, 2);
example:
System.out.println(Byte.parseByte("01100110", 2));

Could write (a String[256] with each manually written 1 and 0 set of 8 bits) it out , its only 256 of them. gives you the ability to check with String.indexOf(binnum[arrayIndex])
and make a corresponding array of new byte[256] and set each in matching order with new Integer(increment).byteValue(), it should reproduce for checking printable over the byte[] array using new Byte(bytarray[incr]).intValue()+"\n"

Related

Long.parseLong throws NumberFormatException for valid hex string [duplicate]

We have a J2ME application that needs to read hex numbers. The application is already too big for some phones so We try not to include any other codec or write our own function to do this.
All the numbers are 64-bit signed integers in hex, when we use Long.ParseLong(hex, 16), it handles positive numbers correctly but it throws exception on negative numbers,
long l = Long.parseLong("FFFFFFFFFFFFFFFF", 16);
How can we get -1 from that hex string using classes provided in Java itself?
Some people may suggest we should write our hex as -1 as Java expected. Sorry, the format is fixed by the protocol and we can't change it.
Your problem is that parseLong() does not handle two's complement - it expects the sign to be present in the form of a '-'.
If you're developing for the CDC profile, you can simple use
long l = new BigInteger("FFFFFFFFFFFFFFFF", 16).longValue()
But the CLDC profile doesn't have that class. There, the easiest way to do what you need is probably to split up the long, parse it in two halves and recombine them. This works:
long msb = Long.parseLong("FFFFFFFF", 16);
long lsb = Long.parseLong("FFFFFFFF", 16);
long result = msb<<32 | lsb;
UPDATE
As of Java 8, you can use parseUnsignedLong():
long l = Long.parseUnsignedLong("FFFFFFFFFFFFFFFF", 16);
Parse it in chunks.
long l = (Long.parseLong("FFFFFFFFF",16)<<32) | Long.parseLong("FFFFFFFF",16);
Worse case scenario, you could check to see if the string is 16 characters that begins with an 8-F, and if so, change that to the equivalent character w/o the most significant bit set (i.e. subtract 8 from that digit), parse the result, and add the parsed value to the lower bound of a signed long? (Essentially just doing the 2's complement yourself.)

Convert long value to char sequence in Java

I would like to convert a long value to a char sequence like in this caluculator here.
I don't really know how that value is converted into the ASCII sequence (or if its even correct). I thought that an ASCII value is 8 bit long so that would mean that I have to convert the long value to binary and then split it into 8 bit blocks, is that correct?
Strictly, ASCII characters are 7 bit long and we usually just add an extra 0 to the beginning to get 8 bits.
Extensions to ASCII (such as ISO 8859) have 8-bit long characters. The calculator you linked seems to be using one of those extensions.
In Java, longs have 64-bits (and one of those bits is used for the sign), so you can indeed have 8 chunks of 8-bit long characters.
First, you'll have to convert your long to a byte array (not all of that question is relevant to this case, but some of it is -- particularly the part that mentions ByteBuffer).
byte[] bytes = ByteBuffer.allocate(8).putLong(someLong).array();
Once you have the array, convert each byte to a char, using a simple cast.
EDIT: Instead of manually converting each character, you may use the java.lang.String(byte[]) constructor.
String str = new String(bytes);
Note that this will use the platform's default charset. If this is not desirable, you can use one of the constructors that also take a charset.
Nope. There are several ways to do this. One way is using java.math.BigInteger which has a method called toByteArray(). Try it if it fits your problem.
Try this code to convert a long value to a 4-char array.
//convert long to char array
long longValIn = 229902744986400000L;
ByteBuffer bb1 = ByteBuffer.allocate(8);
bb1.putLong(longValIn);
char [] charArr = new char[4];
charArr[0] = bb1.getChar(0);
charArr[1] = bb1.getChar(2);
charArr[2] = bb1.getChar(4);
charArr[3] = bb1.getChar(6);
//convert char array to long
ByteBuffer bb2 = ByteBuffer.allocate(8);
bb2.putChar(0,charArr[0]);
bb2.putChar(2,charArr[1]);
bb2.putChar(4,charArr[2]);
bb2.putChar(6,charArr[3]);
long longValOut = bb2.getLong(0);

Wrapper's parseXXX() for signed binary misunderstanding

Let's take Byte.parseByte() as an example as one of the wrappers' parseXXX().
From parseByte(String s, int radix)'s JavaDoc:
Parses the string argument as a signed byte in the radix specified by
the second argument.
But that's not quite true if radix = 2. In other words, the binary literal of -127 is 10000000:
byte b = (byte) 0b10000000;
So the following should be true:
byte b = Byte.parseByte("10000000", 2);
but unfortunately, it throws NumberFormatException, and instead I have to do it as follows:
byte b = Byte.parseByte("-111111", 2);
where parseByte() parses the binary string as a sign-magnitude (the sign and the magnitude), where it should parse as a signed binary (2's complement, i.e. MSB is the sign-bit).
Am I wrong about this?
Am I wrong about this?
Yes. The Javadoc says nothing about 2's-complement. Indeed, it explicitly states how it recognises negative values (i.e. a - prefix, so effectively "human-readable" sign-magnitude).
Think about it another way. If parseByte interpreted radix-2 as 2's-complement, what would you want it to do for radix-10 (or indeed, any other radix)? For consistency, it would have to be 10's-complement, which would be inconvenient, I can assure you!
This is because for parseByte "10000000" is a positive value (128) which does not fit into byte values range -128 to 128. But we can parse two's comlement binary string representation with BigInteger:
byte b = new BigInteger("10000000", 2).byteValue()
this gives expected -128 result

How to convert numbers stored as two character ASCII strings to binary?

I have numbers written as ASCII codes each of 2 bytes which wastes a lot of the space. I want to convert those number to their corresponding ASCII code to save the space.
Any idea?
If you mean characters, Java uses two bytes per character as part of its Unicode support. If you give ASCII values, Java will make the upper byte zero. You won't save a thing.
If you mean floats or doubles or ints, the bytes per value are fixed there as well.
You're barking up the wrong tree. I don't think this will save you anything no matter what you do.
You're better off writing C or C++ if you need that kind of optimization, not Java.
My first thought is that this is an imagined optimization that isn't supported by data. The only application that would justify something like this would be scientific computing on a large scale. Even that wouldn't justify it, because you'll need more precision than a byte per value.
You can use the parse methods on the default types' class. For example, if these numbers are integers and are stored as string "34", you can use Integer.parseInt("34") which returns you a single int whose value is 34. Similarly for Double, Float and Long.
Do you want to convert the Hex number to bytes? If so, this is your answer:
Convert a string representation of a hex dump to a byte array using Java?
If you want to convert number to byte -> http://snippets.dzone.com/posts/show/93
Convert the two digit ASCII string to a byte. When you need the ASCII back just convert it to a string. The following code shows how to do this for "95".
public class Main {
public static void main(String[] args) {
byte b = Byte.parseByte("95");
String bString = "" + b;
}
}
If you need to change the way they are stored in a file, just read the two digit text numbers in as strings and write them out to another file as bytes.

NumberFormatException while converting from string to byte

I am coming across a strange thing. I have a number in binary in the form of string particularly "01001100". But I am getting the exception mentioned above by executing the following code.
String s = "01001100";
byte b = Byte.parseByte(s);
But why is it happening? Whereas in a byte we can store max no. upto 127 and min. upto -128.
And the decimal equivalent of the above number is 76 which is perfectly in the range.
The particular exception I am getting is as:
java.lang.NumberFormatException:Value out of range. value:01001100 radix:10
Is there any way to get rid of it. Yes and it is compulsory for me to use byte only as I am extracting the data stored in the image byte by byte only.
Thank you.
The key is at the end of the exception string: radix:10. You are converting the decimal value 1,001,100 to a byte, and it does not fit. Try this:
String s = "01001100";
byte b = Byte.parseByte(s, 2);
01001100 is a fairly large number in decimal (over a million; see the docs for parseByte(String)). You probably want the version that accepts a radix:
byte b = Byte.parseByte(s, 2);

Categories