Converting integers into bytes - java

How do the following numbers, on byte conversion give the results on right hand side ? I guess when you convert an integer to a byte array, it should convert each of the digit of that number into its correponding 4 byte array. But here's what cannot understand..
727 = 000002D7
1944 = 00000798
42 = 0000002A
EDIT: I was reading a blog where I found these following lines:-
If we are working with integer column names, for example, then each column name is 4 bytes long. Lets work with column names 727, 1944 and 42.
The bytes associated with these three numbers:
727 = 000002D7
1944 = 00000798
42 = 0000002A
link to this blog: http://www.divconq.com/2010/why-does-cassandra-have-data-types/

Solution
The following will give you the exact output as in your example:
public class Main
{
public static void main(final String[] args)
{
System.out.format("%08X\n", 727);
System.out.format("%08X\n", 1944);
System.out.format("%08X\n", 42);
}
}
and here is the expected output:
000002D7
00000798
0000002A
Explanation
How the Formatter works, the format from right to left string says, x = format as hexadecimal, 08 = pad to the left eight characters with 0 and the % marks the beginning of the pattern.
You can also use String.format("%08X", 727); to accomplish the same thing.

Related

IOStream writing data to console

I have read that only lower order 8 bits are used while Output of byte output stream, then why I am getting 5?
Also, why I am not getting the binary or hex format of 65?
If I delete the leading 2 zeros and make the value of b as 65 then I get 'A' as the answer but why by placing leading 2 zeros I am not getting the answer but '5'?
Also why I am getting the answer as a character and not in binary format as 'out' is a Byte OutputStream object and should write in bytes?
public static void main(String[] args) {
int b = 0065;
System.out.write(b);
System.out.flush();
}
desired 'A', actual 5?
Also, desired 0100 0001.
Static field out in class java.lang.System has type java.io.PrintStream.
Class PrintStream has several write() methods. In your code, the argument you are passing to method write() is an int, hence the method invokde is write(int). You are assigning a number literal to your local variable b. In java, a number literal that begins with a zero (0) indicates an octal number and 65 in octal is 53 (fifty-three) in decimal and 53 is the ASCII code for the digit 5 (five). For your information, class java.lang.Integer has static method toBinaryString(). I suggest you look at the javadoc for that method.
public class StackOverFlow{
public static void main(String []args){
int x = 0065;// in java when you append zero like 011 or 0023 its take as octal number,when you print it will convert to decimal
System.out.println(x); // 0065 is octal value when you convert to decimal it will be 53 and in hexa 35
int y = 056;//octal value
System.out.println(y); // Output:46 decimal value
}
}
Because 0065 is octal for decimal 53 for hexadecimal 0x35 for the ASCII character 5.

Compiler error "Incompatible types" on byte literal

I have seen many cases where a byte is declared but where the value from a method like
intToByte or StringToByte is casted to a byte because the programmer is provideing i.e. a hexadecimal- value, an Integer- or a String-value.
I am trying to assign an actual byte value to the variable without any casting or methods to parse, like so:
public class ByteTest {
/**
* This array will be used to hold three characters, together forming a string.
*/
private static byte[] string;
/**
* The main method of the program, where the byte-array is coming to use.
*/
public static void main(String args[]) {
//Construct the array with a limit to three bytes.
string = new byte[3];
/*
* Fill the three bytes with the binary values to create "O", "l" and "e".
*/
string[0] = 01001111;
string[1] = 01101100;
string[2] = 01100101;
//Print out "Ole".
System.out.println(string[0] + string[1] + string[2]);
}
}
But I get the following error in the compiler:
java\ByteTest.java:8: error: incompatible types: possible lossy conversion from int to byte
string[0] = 01001111;
^
java\ByteTest.java:9: error: incompatible types: possible lossy conversion from int to byte
string[1] = 01101100;
^
java\ByteTest.java:10: error: incompatible types: possible lossy conversion from int to byte
string[2] = 01100101;
^
Appearently, what I think of as eight bits, the compiler thinks of as eight integers.
Is there any other solution to this, where I can provide actually bits directly to the variables/array?
Indicate binary
string[0] = 0b01001111;
string[1] = 0b01101100;
string[2] = 0b01100101;
This reminds me of the joke: there are 10 kinds of programmers: those that understand binary and those that do not.
As bytes are signed there still is a problem with 0b1xxxxxxx which would need to be a negative number. In that case use the following trick:
string[2] = 0b11100101 - 256;
string[2] = (byte) 0b11100101; // Or simply cast the int range value.
Also binary is ideal for an underscore usage:
string[2] = 0b0110_0101; // 0x65
And is commented by #BackSlash: bytes are binary data. To interprete them as text they have to be associated with some Charset/encoding.
String s = new String(string, StandardCharsets.US_ASCII);
System.out.println(s);
This converts the bytes, interpreting them as ASCII to the Unicode that String uses (to combine all scripts of the world).
Adding 0 in front of constant number ( like 01101100 ) is interpreted as octal value
What do you need to do to fix this?
The simplest solution which will use the least memory (code and data) is also the simplest.
private static final String string = "Ole";
System.out.println(string);
otherwise you can do this
private static final char[] chars = {
(char) 0b01001111,
(char) 0b01101100,
(char) 0b01100101 };
String s = new String(chars);
System.out.println(s);
Note: characters in Java are 16-bit unsigned char, not 8 bit byte
To get an idea of why the class file is bigger you can dump the class file with
java -c -v -cp target/classes mypackage.MyClass
To start with 01001111 is in octal, not binary. To write a binary number, you need 0b01001111
Numbers don't "remember" how many leading zeros you gave it, and generally speaking, leading zeros are dropped when printed.
The default format for a number is decimal, not binary.
When you add two, or three numbers, you get another number. Assuming you got this to compile it would print something like
288
or whatever the sum of the values are.
BTW it is really confusing to name an int called "string" because this could be assumed to be a String
Assign Actual value :-
String a ="100101";
System.out.println(""+a);
Output :- 100101
Binary to integer conversion and then assign value to string variable :-
String a=""+0b100101
System.out.println(""+a);
Output: 37

Convert Binary String to Binary

How do I convert a String written as Binary, to binary (in byte array)?
If I have a String:
String binary = "0000"
I want the binary data to be 0000.
below is what happens when I set the binary to a byte array (which in turn returns 48, which is ASCII)
Binary String: 0000
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
I'm not good at explaining so hopefully the above example was enough to tell you what I want.
EDIT: This is to set the data into a binary file.
Use this:
System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100
Maybe you want this:
int i = Integer.valueOf(binary, 2); // ie base 2
This call expects the input to be a string of 0 and 1 chars.
Then if you want an array of bytes:
byte[] bytes = new ByteBuffer().putInt(i).compact().array();
Convert into Decimal from Binary
System.out.println(new BigInteger("1010",2).toString()); // 10 decimal
Convert into Binary/Octal/Hex from Decimal
You can use BigInteger#toString(radix) method to get value in any radix.
System.out.println(new BigInteger("10").toString(2)); // 1010 binary
System.out.println(new BigInteger("10").toString(8)); // 12 octal
System.out.println(new BigInteger("10").toString(16)); // a hexadecimal
Let me explain you a bit more how it works with different base
(10)10 = (1010)2
(10)10 = (12)8
(10)10 = (a)16
JBBP framework has in utils a special method to convert a string contains a binary defined data into byte array
byte [] converted = JBBPUtils.str2bin("00000000");

XOR hex ascii values of letters

I'm trying to complete some homework and am totally stumped. The function I need to perform is, given the hexadecimal value of a character, xor it with another hex value to verify a known end value.
Giving a simple example (the one given to me), I know that the ascii value of 'Bob' would be [42,6F,62], and 'Eve' would be [45,76,65]. I have to XOR 'Bob''s value with [07,16,17] to get 'Eve'.
I thought that xor was simply addition modulo base, but simply using the Microsoft Calculator: (42 + 45) mod 16 = 3 but 42 XOR 45 = 7. I do not understand how else the XOR function would be done. Can someone please explain?
Thanks in advance
I tried
float l = (6F)^(16);
System.out.println(l);
and got this exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - bad operand types for binary operator '^'
first type: float
second type: double
at p2p_example.P2P_Example.main(P2P_Example.java:40)
Java Result: 1
XOR is a bitwise exclusive-or,
42 = 1000010
45 = 1000101
7 = 0000111
That is a one if there is one (and only one) one in the two bits being XORd. For Java, you can use parseInt and pass in the radix, for example
public static void main(String[] args) {
int a = Integer.parseInt("42", 16);
int b = Integer.parseInt("45", 16);
System.out.println(Integer.toString(a ^ b, 16));
}
prints
7
0x42 + 0x45 = 0x87
= 135
135 % 16 = 7 = 0x07
I think you're getting confused between hex and decimal bases (though (42+45)%16 also happens to be 7 in decimal; so maybe you're just doing your math wrong?)

Can I multiply charAt in Java?

When I try to multiply charAt I received "big" number:
String s = "25999993654";
System.out.println(s.charAt(0)+s.charAt(1));
Result : 103
But when I want to receive only one number it's OK .
On the JAVA documentation:
the character at the specified index of this string. The first character is at index 0.
So I need explanation or solution (I think that I should convert string to int , but it seems to me that is unnesessary work)
char is an integral type. The value of s.charAt(0) in your example is the char version of the number 50 (the character code for '2'). s.charAt(1) is (char)53. When you use + on them, they're converted to ints, and you end up with 103 (not 100).
If you're trying to use the numbers 2 and 5, yes, you'll have to parse them. Or if you know they're standard ASCII-style digits (character codes 48 through 57, inclusive), you can just subtract 48 from them (as 48 is the character code for '0'). Or better yet, as Peter Lawrey points out elsewhere, use Character.getNumericValue, which handles a broader range of characters.
Yes - you should parse extracted digit or use ASCII chart feature and substract 48:
public final class Test {
public static void main(String[] a) {
String s = "25999993654";
System.out.println(intAt(s, 0) + intAt(s, 1));
}
public static int intAt(String s, int index) {
return Integer.parseInt(""+s.charAt(index));
//or
//return (int) s.charAt(index) - 48;
}
}

Categories

Resources