I want to read a binary file and do some manipulation on each byte. I want to test that I am manipulating the bytes correctly. I want to set a byte variable1 to "00000000" and then another byte variable2 set at "00001111" and OR them newvariable = variable1|variable2, shift the newvariable << 4 bits and then print out the int value.
byte a = 00000000;
//Convert first oneByte to 4 bits and then xor with a;
byte b = 00001111;
byte c = (byte)(a|b);
c = c << 4;
System.out.println("byte= " + c + "\n");
I am not sure why I keep getting "incompatiable types:possible lossy conversion from byte to int"
You need to put a '0b' in front of those numbers to express binary constants. The number 00001111 is interpreted as a literal in octal, which is 585 in decimal. The max byte is 127 (since it's signed). Try 0b00001111 instead.
As literals, those will still be int, so depending on where you do the assignment, you may also need to explicitly cast down to byte.
Related
I've got a huge string of bits (with some \n in it too) that I pass as a parameter to a method, which should isolate the bits 8 by 8, and convert them all to bytes using parseInt().
Thing is, every time the substring of 8 bits starts with a 1, the resulting byte is a negative number. For example, the first substring is '10001101', and the resulting byte is -115. I can't seem to figure out why, can someone help? It works fine with other substrings.
Here's my code, if needed :
static String bitsToBytes(String geneString) {
String geneString_temp = "", sub;
for(int i = 0; i < geneString.length(); i = i+8) {
sub = geneString.substring(i, i+8);
if (sub.indexOf("\n") != -1) {
if (sub.indexOf("\n") != geneString.length())
sub = sub.substring(0, sub.indexOf("\n")) + sub.substring(sub.indexOf("\n")+1, sub.length()) + geneString.charAt(i+9);
}
byte octet = (byte) Integer.parseInt(sub, 2);
System.out.println(octet);
geneString_temp = geneString_temp + octet;
}
geneString = geneString_temp + "\n";
return geneString;
}
In Java, byte is a signed type, meaning that when the most significant bit it set to 1, the number is interpreted as negative.
This is precisely what happens when you print your byte here:
System.out.println(octet);
Since PrintStream does not have an overload of println that takes a single byte, the overload that takes an int gets called. Since octet's most significant bit is set to 1, the number gets sign-extended by replicating its sign bit into bits 9..32, resulting in printout of a negative number.
byte is a signed two's complement integer. So this is a normal behavior: the two's complement representation of a negative number has a 1 in the most-significant bit. You could think of it like a sign bit.
If you don't like this, you can use the following idiom:
System.out.println( octet & 0xFF );
This will pass the byte as an int while preventing sign extension. You'll get an output as if it were unsigned.
Java doesn't have unsigned types, so the only other thing you could do is store the numbers in a wider representation, e.g. short.
In Java, all integers are signed, and the most significant bit is the sign bit.
Because parseInt parse signed int that means it converts the binary if it begins with 0 its positive and if 1 its negative try to use parseUnsignedInt instead
based on this array :
final char[] charValue = { 'u', ' ', '}','+' };
i want to print the double value and the ascii value from it in Java.
i can't find a proper solution for that in internet. I just found how to convert a single Character into Integer value. But what about many characters?
the main problem is, i have a large char[] and some double and int values are stored in. for double values they are stored within 4 bytes size and integer 1 or 2 bytes so i have to read all this and convert into double or integer.
Thanks for you help
When java was designed, there was C char being used for binary bytes and text.
Java made a clear separation between binary data (byte[], InputStream/OutputStream) and Unicode text (char, String, Reader/Writer). Hence Java has full Unicode support. The binary data, byte[], need information: their used encoding, in order to be convertable to text: char[]/String.
In Java a char[] will rarely be used (as in C/C++), and it seems byte[] is intended, as you mention 4 elements to be used for an int etcetera. A char is 16 bits, containing UTF-16 text.
For this case one can use a ByteBuffer either wrapping a byte[] or being taken from a memory mapped file.
Writing
ByteBuffer buf = ByteBuffer.allocate(13); // 13 bytes
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
buf.putInt(42); // at 0
buf.putDouble(Math.PI); // at 4
buf.put((byte) '0'); // at 12
buf.putDouble(4, 3.0); // at 4 overwrite PI
byte[] bytes = buf.array();
Reading
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
int a = buf.getInt();
double b = buf.getDouble();
byte c = buf.get();
String boxVal = "FB";
Integer val = Integer.parseInt(boxVal, 16);
System.out.println(val); //prints out 251
byte sboxValue = (byte) val;
System.out.println("sboxValue = " + Integer.toHexString(sboxValue)); //fffffffb
The last line should print out "fb". I am not sure why it prints out "fffffffb."
What am I doing wrong? How should I fix my code to print "fb"?
You have an overflow when you convert 251 to a byte. Byte has a minimum value of -128 and a maximum value of 127 (inclusive)
See here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Why does it print "fffffffb": because you first convert the byte value (which is -5) to an integer with value -5 and then print that integer.
The easiest way to get the output you want is:
System.out.printf("sboxValue = %02x\n", sboxValue);
Or, you could also use:
System.out.println("sboxValue = " + Integer.toHexString(sboxValue & 0xff));
What happens here in detail:
the byte value fb is converted to an integer. Since the value is negative, as you can see because the leftmost bit is 1, it is sign extended to 32 bits: fffffffb.
By masking out the lower 8 bits (with the bitwise and operation &) we get the integer value 000000fb.
i am working on a project that gets the data from the file into a byte array and adds "0" to that byte array until the length of the byte array is 224 bits. I was able to add zero's but i am unable to confirm that how many zero's are sufficient. So i want to print the file data in the byte array in binary format. Can anyone help me?
For each byte:
cast to int (happens in the next step via automatic widening of byte to int)
bitwise-AND with mask 255 to zero all but the last 8 bits
bitwise-OR with 256 to set the 9th bit to one, making all values exactly 9 bits long
invoke Integer.toBinaryString() to produce a 9-bit String
invoke String#substring(1) to "delete" the leading "1", leaving exactly 8 binary characters (with leading zeroes, if any, intact)
Which as code is:
byte[] bytes = "\377\0\317\tabc".getBytes();
for (byte b : bytes) {
System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}
Output of above code (always 8-bits wide):
11111111
00000000
11001111
00001001
01100001
01100010
01100011
Try Integer.toString(bytevalue, 2)
Okay, where'd toBinaryString come from? Might as well use that.
You can work with BigInteger like below example, most especially if you have 256 bit or longer.
Put your array into a string then start from there, see sample below:
String string = "10000010";
BigInteger biStr = new BigInteger(string, 2);
System.out.println("binary: " + biStr.toString(2));
System.out.println("hex: " + biStr.toString(16));
System.out.println("dec: " + biStr.toString(10));
Another example which accepts bytes:
String string = "The girl on the red dress.";
byte[] byteString = string.getBytes(Charset.forName("UTF-8"));
System.out.println("[Input String]: " + string);
System.out.println("[Encoded String UTF-8]: " + byteString);
BigInteger biStr = new BigInteger(byteString);
System.out.println("binary: " + biStr.toString(2)); // binary
System.out.println("hex: " + biStr.toString(16)); // hex or base 16
System.out.println("dec: " + biStr.toString(10)); // this is base 10
Result:
[Input String]: The girl on the red dress.
[Encoded String UTF-8]: [B#70dea4e
binary: 101010001101000011001010010000001100111011010010111001001101100001000000110111101101110001000000111010001101000011001010010000001110010011001010110010000100000011001000111001001100101011100110111001100101110
hex: 546865206769726c206f6e20746865207265642064726573732e
You can also work to convert Binary to Byte format
try {
System.out.println("binary to byte: " + biStr.toString(2).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {e.printStackTrace();}
Note:
For string formatting for your Binary format you can use below sample
String.format("%256s", biStr.toString(2).replace(' ', '0')); // this is for the 256 bit formatting
First initialize the byte array with 0s:
byte[] b = new byte[224];
Arrays.fill(b, 0);
Now just fill the array with your data. Any left over bytes will be 0.
can you increment a hex value in Java? i.e. "hex value" = "hex value"++
It depends how the hex value is stored. If you've got the hex value in a string, convert it to an Integer, increment and convert it back.
int value = Integer.parseInt(hex, 16);
value++;
String incHex = Integer.toHexString(value);
Short answer: yes. It's
myHexValue++;
Longer answer: It's likely your 'hex value' is stored as an integer. The business of converting it into a hexadecimal (as opposed to the usual decimal) string is done with
Integer.toHexString( myHexValue )
and from a hex string with
Integer.parseInt( someHexString, 16 );
M.
What do you mean with "hex value"? In what data type is your value stored?
Note that int/short/char/... don't care how your value is represented initially:
int i1 = 0x10;
int i2 = 16;
i1 and i2 will have the exact same content. Java (and most other languages as well) don't care about the notation of your constants/values.
Yes. All ints are binary anyway, so it doesn't matter how you declare them.
int hex = 0xff;
hex++; // hex is now 0x100, or 256
int hex2 = 255;
hex2++; // hex2 is now 256, or 0x100
The base of the number is purely a UI issue. Internally an integer is stored as binary. Only when you convert it to human representation do you choose a numeric base. So you're question really boils down to "how to increment an integer?".