Java: have integer, need it in byte in 0x00 format - java

I have an integer used to seed my for loop:
for(int i = 0; i < value; i++)
Within my for loop I am seeding a byte array with byte content values that increment +1. For instance new byte[]{0x00}; But the 0x00 needs to be 0x01 on the next iteration, how can I convert my value of integer i into a value of byte in the 0x00 format?
I tried things like Byte.valueOf(Integer.toHexString(i)) but this just gives me a value that looks like 0 instead of 0x00.

new byte[]{0x00}
is actually equivalent to
new byte[]{0}
The 0x00 notation is just an alternative way to write integer constants, and if the integer constant is in the range -128 to 127, then it can be used as a byte.
If you have an existing integer variable that you want to use, and its value is in the range -128 to 127, then you just have to cast it:
int i = 1;
new byte[]{(byte)i};

I think the real problem is that you are confused about number representations and text renderings of numbers. Here are some key facts that you need to understand:
The byte type is the set of integral values from -128 to +127.
All integral types use the same representation (2's complement). The difference between the different types is their ranges.
When you "see" a number, what you are seeing is a rendering of the number into a sequence of characters. There are MANY possible renderings; e.g. the number represented in memory as 00101010 (42) can be rendered as "42" or "+42" or "0x2a" or ... "forty two".
The default format for rendering a byte, short, int and long is the same; i.e. an optional minus sign followed by 1 or more decimal digits (with no zero padding). If you want to see your numbers formatted differently, then you need to do the formatting explicitly; e.g. using String.format(...).
So to pull this together, if you want the bytes to look like 0x00 and 0x01 when you output or display them, you need to format them appropriately as you output / display them. In your example code, I doubt that there is anything wrong with the numbers themselves, or with the loop you are using to populate the array.

You are confusing the string representation of the value with the value itself. A value can be represented as binary, decimal, or hex, but it is still the same value.
If you want to use your integer to initialise a byte array, you just need to cast your integer value to a byte value as follows:
arr[i] = (byte) i;

You want
new byte[]{(byte)i}
How you print this array is another matter. Look up printf in the API reference.

I would just like to note that 0 is NOT the same thing as 0x00. If i were to use:
ColorChooserOutputText.append(Integer.toHexString(list[i].getRed()));
ColorChooserOutputText.append(Integer.toHexString(list[i].getGreen()));
ColorChooserOutputText.append(Integer.toHexString(list[i].getBlue()));
and wanted to return the color, Purple it would return: ff0cc Which would be fine if I were just using Java. But if you are going between Java and something that had format specific needs ff0cc would not produce purple.. ff00cc is actually purple.
//Declare some variables.
Color HexColor = JButton1.getBackground();
String MyRValue = null;
String MyGValue = null;
String MyBValue = null;
//Get Hex Value
MyRValue = Integer.toHexString(HexColor.getRed());
MyGValue = Integer.toHexString(HexColor.getGreen());
MyBValue = Integer.toHexString(HexColor.getBlue());
//Make sure to keep both 0's
MyRValue = ("00"+MyRValue).substring(MyRValue.length());
MyGValue = ("00"+MyGValue).substring(MyGValue.length());
MyBValue = ("00"+MyBValue).substring(MyBValue.length());
//Format your HexColor to #00ff00, #000000, #ff00ee
JTextArea1.append("#");
JTextArea1.append(MyRValue+MyGValue+MyBValue);
JTextArea1.append(", ");

String.Format ("%02x") is your friend :)
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
http://www.xinotes.org/notes/note/1195/

Related

How do you make a byte into a binary number and not to a string in java

When I want to print the binary number of a byte, I have to do:
byte byte1 = 16;
String byteString = Integer.toBinaryString(byte1);
System.out.println(byteString);
This makes the byte into a string, but when I try to parse it into a byte, it makes it into a base 10 number again, Is there a way to make a byte into a binary number byte, and not to a base-10? I want to make it so that if you printed the byte, it would print the binary. do you have to tell it to print the Binary every time?
I want to know if there is a way to make it print the binary representation of the byte every time, instead of having to convert it to a binary string every time, and without making a new string variable to print.
You don't need a String variable because you can just do this:
System.out.println(Integer.toBinaryString(a));
but there is no way to make the conversion happen automatically without using toBinaryString. If this code is too long, you could make a simple method like this
public static void printInBinary(int a) {
System.out.println(Integer.toBinaryString(a));
}
As you have identified, both approaches will result in unnecessary work if you need to print the same number repeatedly, but you do not need to worry about this. Worrying about stuff like that is a waste of time (99% of the time).
Because of programmer efficiency.
At physical level, computers do not have the concept of neither "binary" numbers nor "decimal" numbers (I mean, in form of "110011" or "123"). It's all electrical impulses in there. When you are printing a number onto the screen, it ALWAYS has to convert the "impulses" into characters on your screen in one way or another.
When the number is stored in memory as a "number", it is not compatible with neither decimal nor binary representation. Converting the "number" into a "string" of any kind requires approximately same amount of computing power.
Let's say you have this code:
byte byte1 = 16;
String byteString = Integer.toBinaryString(byte1);
System.out.println(byteString);
System.out.println(byte1);
In reality, the operations performed by the cpu would look something like this:
String byteString = Integer.toBinaryString(byte1);
String decimalString = toDecimalString(byte1);
System.out.println(byteString);
System.out.println(decimalString);
That is, unless you save your number as String already, your CPU has to do extra work to convert it into either decimal or hexadecimal or binary representation. It is just that by default a decimal representation is chosen. And, there is no way to somehow "switch" this default representation neither for one variable nor globally for entire application.
Therefore, you need to convert it to binary every time you want a variable of any numeric type printed on the screen as a character.
What about Byte.parseByte(s, radix)?
System.out.println(Byte.parseByte("10000", 2)); // prints 16
What about this:
byte byte1 = 76;
StringBuilder byteString = new StringBuilder();
for (int i = 128; i > 0; i /= 2) {
if ((byte1 & i) == 0) {
byteString.append(0);
} else {
byteString.append(1);
}
}
System.out.println(byteString);

Converting a int to char and then back to int - doesn't give same result always

I am trying to get a char from an int value > 0xFFFF. But instead, I always get back the same char value, that when cast to an int, prints the value 65535 (0xFFFF).
I couldn't understand why it is generating symbols for unicode > 0xFFFF.
int hex = 0x10FFFF;
char c = (char)hex;
System.out.println((int)c);
I expected the output to be 0x10FFFF. Instead, the output comes back as 65535.
This is because, while an int is 4 bytes, a char is only 2 bytes. Thus, you can't represent all values in a char that you can in an int. Using a standard unsigned integer representation, you can only represent the range of values from 0 to 2^16 - 1 == 65535 in a 2-byte value, so if you convert any number outside that range to a 2-byte value and back, you'll lose data.
int is 4 byte. char is 2 byte.
Your number was well within range an int can hold, but not which char can.
So when you converted that number to a char, it lost data and became the maximum a char can hold, which is what it printed i.e. 65535
Your number was too big to be a char which is 2 bytes. But it was small enough where it fit in as an int which is 4 bytes. 65535 is the biggest amount that fits in a char so that's why you got that value. Also, if a char was big enough to fit your number, when you returned it to an int it might have returned the decimal value for 0x10FFFF which is 1114111.
Unfortunately, I think you were expecting a Java char to be the same thing as a Unicode code point. They are not the same thing.
The Java char, as already expressed by other answers, can only support code points that can be represented in 16 bits, whereas Unicode needs 21 bits to support all code points.
In other words, a Java char on its own, only supports Basic Multilingual Plane characters (code points <= 0xFFFF). In Java, if you want to represent a Unicode code point that is in one of the extended planes (code points > 0xFFFF), then you need surrogate characters, or a pair of characters to do that. This is how UTF-16 works. And, internally, this is how Java strings work as well. Just for fun, run the following snippet to see how a single Unicode code point is actually represented by 2 characters if the code point is > 0xFFFF:
// Printing string length for a string with
// a single unicode code point: 0x22BED.
System.out.println("πΆ―­".length()); // prints 2, because it uses a surrogate pair.
If you want to safely convert an int value that represents a Unicode code point to a char (or chars to be more exact), and then convert it back to an int code point, you will have to use code like this:
public static void main(String[] args) {
int hex = 0x10FFFF;
System.out.println(Character.isSupplementaryCodePoint(hex)); // prints true because hex > 0xFFFF
char[] surrogateChars = Character.toChars(hex);
int codePointConvertedBack = Character.codePointAt(surrogateChars, 0);
System.out.println(codePointConvertedBack); // prints 1114111
}
Alternatively, instead of manipulating char arrays, you can use a String, like this:
public static void main(String[] args) {
int hex = 0x10FFFF;
System.out.println(Character.isSupplementaryCodePoint(hex)); // prints true because hex > 0xFFFF
String s = new String(new int[] {hex}, 0, 1);
int codePointConvertedBack = s.codePointAt(0);
System.out.println(codePointConvertedBack); // prints 1114111
}
For further reading: Java Character Class

parseInt on a string of 8 bits returns a negative value when the first bit is 1

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

How to store Hex string in an Integer variable in android???

In the following code intArray[i] stores RGB values of pixels in hex format(eg:0xffff0000) .... The method hsvToRgb() gives bak an integer value of RGB (eg:15777252) but i need back the rgb value in the original hex format after changes.
The second line gives me that but its a string ....What do i do to store this string value back into the array? ... please help me.
int disco = hsvToRgb(hsv);
hexColor = String.format("0x%06X", (0xffffff & disco));
intArray[i] = Integer.valueOf(String.valueOf(disco), 16);
There's no such thing as a "hex format" integer versus a "decimal format" integer. The bit/byte representation of the value is the same. For example, the decimal value 15,777,252 is the hex value 0xF0BDE4. (You can use Google to convert: search "15777252 in hex").
You can use the disco value directly. If you want to print it out in a hex representation, use Integer.toHexString().
Regarding the format. Think of it like this ... The computer represents the value as a series of bits. By way of example, let's pick a random number and represent it using 8 bits: 01110101. Using a bit string to represent bigger numbers would get very long very quickly, so hexadecimal is often used. The hex equivalent is: 65. By convention, we usually precede the value by 0x when it's in hex. That gives us 0x65. Non-programmers tend to deal more naturally in base 10 however (rather than base 16). The same number in base 10 is 101.
You can see this with some code:
final int value = 0x65; // we can declare it in hex
final int sameValue = 101; // or in decimal
System.out.println(value); // output in base 10; prints "101"
System.out.println(Integer.toHexString(value)); // output in base 16; prints "65"
System.out.println(Integer.toBinaryString(value)); // output in base 2; prints "1100101"
System.out.println(""+(value == sameValue)); // prints "true"

How can I convert an int number from decimal to binary?

How can I convert an int number from decimal to binary. For example:
int x=10; // radix 10
How can I make another integer has the binary representation of x, such as:
int y=1010; // radix 2
by using c only?
An integer is always stored in binary format internally -- saying that you want to convert int x = 10 base 10 to int y = 1010 base 2 doesn't make sense. Perhaps you want to convert it to a string representing the binary format of the integer, in which case you can use Integer.toBinaryString.
First thing you should understand is that a value is an abstract notion, that is not bounded to any representation. For example, if you have 20 apples, the number of apples will be the same regardless of the representation. So, dec("10") == bin("1010").
The value of an int reffers to this abstract notion of value, and it does not have any form until you with to print it. This means that the notion of base is important only for conversions from string to int and back.
String s = Integer.toBinaryString(10);
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Whether it's binary or decimal doesn't really have anything to do with the integer itself. Binary or decimal is a property of a physical representation of the integer, i.e. a String. Thus, the methods you should look at are Integer.toString() and Integer.valueOf() (the versions that take a radix parameter).
BTW, internally, all Java integers are binary, but literals in the source code are decimal (or octal).
Your question is a bit unclear but I'll do my best to try to make sense of it.
How can I make another integer has the binary representation of x such as: int y=1010 radix 2?
From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.
You can write your number as a string instead and use Integer.parseInt with the desired radix:
int y = Integer.parseInt("1010", 2);
But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.
If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.
Both integers will have the same interior representation, you can however display as binary via Integer.toBinaryString(i)
Use Integer.toBinaryString()
String y = Integer.toBinaryString(10);
Converting an integer to another base (string representation):
int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"
Converting the string back into an integer
String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15
This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)
int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)

Categories