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);
Related
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"
Let's say I have a byte array and I try to encode it to UTF_8 using the following
String tekst = new String(result2, StandardCharsets.UTF_8);
System.out.println(tekst);
//where result2 is the byte array
Then, I get the bytes using getBytes() with values from 0 to 128
byte[] orig = tekst.getBytes();
And then, I wish to do a frequency count of my byte[] orig using the ff:
int frequencies = new int[256];
for (byte b: orig){
frequencies[b]++;
}
Everything goes well till I encounter an error which states
java.lang.ArrayIndexOutOfBoundsException: -61
Does that mean that my byte still contains negative values despite converting it to UTF-8? Is there something wrong that I'm doing? Can someone please give me clarity on this cause I'm still a beginner on the subject. Thank you.
Answering the specific question
Does that mean that my byte still contains negative values despite converting it to UTF-8?
Yes, absolutely. That's because byte is signed in Java. A byte value of -61 would be 195 as an unsigned value. You should expect to get bytes which aren't in the range 0-127 when you encode any non-ASCII text with UTF-8.
The fix is easy: just clamp the range to 0-255 with a bit mask:
frequencies[b & 0xff]++;
Addressing what you're attempting to do
This line:
String tekst = new String(result2, StandardCharsets.UTF_8);
... is only appropriate if result2 is genuinely UTF-8-encoded text. It's not appropriate if result2 is some arbitrary binary data such as an image, compressed data, or even text encoded in some other encoding.
If you want to preserve arbitrary binary data as a string, you should use something like Base64 or hex. Basically, you need to determine whether your data is inherently textual (in which case, you should use strings for as much of the time as possible, and use an appropriate Charset to convert to binary where necessary) or inherently binary (in which case you should use bytes for as much of the time as possible, and use base64 or hex to convert to text where necessary).
This line:
byte[] orig = tekst.getBytes();
... is almost always a bad idea. It uses the platform-default encoding to convert a string to bytes. If you really, really want to use the platform-default encoding, I would make that explicit:
byte[] orig = tekst.getBytes(Charset.defaultCharset());
... but this is an extremely unusual requirement these days. It's almost always better to stick to UTF-8 everywhere.
My android program need to receive int values from arduino analog sensor via usb and print them on real time graph, i receive byte[] from call back function.
i tried many ways to convert from byte[] to string or int include new String new Integer BigInteger parseInt and some code method that i find in other topics, but nothing work i receive only half of the correct values, other values to much bugger or smaller.
The byte[] length changed from 1 to 4 , their is some empty bytes, it look like this(log):
How i can to convert it to correct values? where the problem?
In ideal i need receive int values between 230 to 300 from sensor.
It seems that your sensor is using text protocol. If I convert your bytes to ASCII chars, it will be:
..
10-LF
50-2
53-5
56-8
..
13-CR
10-LF
50-2
53-5
..
54-6
13-CR
10-LF
etc.
Interpreted as
258
256
so, I thing the best solution is to accumulate received bytes as chars and when CRLF is reveived, read whole string (with stripped CRLF) as int - probably via parseInt.
Arduino code segment?
Guessing badly : int is a 16 bit value byte is 8 bits.
Int_8 is -128 to 127 . uint8_t 0-255 not supported by java as far as i know but you can use the char type unsigned 16 bit(need to cast it).
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);
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.