(bye) Byte.MAX_VALUE + 1 == Byte.MIN_VALUE ?
Hi
(bye) Byte.MAX_VALUE + 1 == Byte.MIN_VALUE
the above expression is evaluated as true. why is it so?
according to my understanding 128 is not equals to -128.
please explain. i'm new to java.
Thx
Hi
(bye) Byte.MAX_VALUE + 1 == Byte.MIN_VALUE
the above expression is evaluated as true. why is it
so?
according to my understanding 128 is not equals to
-128.0x7F + 1 == 0x80
Similar Messages
-
hi,
i am new to java. And i need to store 0xef into a byte. how do i do that ?
byte [] b = new byte[] { (byte) 0x00, (byte)0xef, (byte)(0xff) };
I always ended up getting 3f for 0xef.
Also understand that :
Byte.MIN_VALUE = -128
Byte.MAX_VALUE = 127
thanks.
LeeYou just do it. The fact that EF (when it's in a byte) will be interpreted as a negative number doesn't have any effect.
Where do you get the 3F? You probably have some conversion problems. -
How to show an image in JSP given the bytes[] of the photo?
Hi all,
I stored a user's picture in the db as text. For this I simply converted the JPG to bytes[] and from bytes to string: Base64.encode(bytes)
Now I wish to do the reverse - to 'output' the image on the screen. So given the bytes[] of the image with
byte[] bytesDB = Base64.decode(userPhotoStr); //userPhotoStr is something like this: /9j/4AAQSkZJRgA...Question: How can I show the image in the JSP page embedded in the page not as download?
I'm using struts with JSP pages.
Thank you!!!!Images in HTML are to be displayed using <img> element. All what an <img> element can take as image is an URL pointing to the image in question.
If the image is dynamic, then you can just let that URL point to some Servlet which takes some request parameter or reads the path info, reads/gets the image as byte array or (much more efficient) as inputstream and writes it to the outputstream of the response.
You may get some ideas out of this: [http://balusc.blogspot.com/2007/04/imageservlet.html].
By the way, massaging the byte array from/to a String is a terribly bad idea. Just store bytes as computer readable bytes, not as human readable characters, this makes completely no sense. Characters on its turn have to be converted to bytes again after all, but now you've let the DB do the work. All with all a performance pain. Bytes > Chars > Bytes > Chars > Bytes instead of just Byes > Bytes. In database you normally use BLOB, BINARY or equivalent for this in combination with JDBC's PreparedStatement#setBinaryStream() and ResultSet#getBinaryStream(). -
Now i have a simple conversation program and i have to encrypt my content which i talked about, and i did it.
But i don't know hot to decrypt it....
because i don't know how can a string translate to byte[] without encoding....i have such codes like this
input = new BufferedReader( new InputStreamReader( client.getInputStream() ) ) ;
output = new PrintStream( client.getOutputStream() ) ;
while( ( message = input.readLine() ) != null ) {
try
cipher.init(Cipher.DECRYPT_MODE, KEY) ;
decrypt = cipher.doFinal(message.getBytes()) ;
catch(Exception e)
e.printStackTrace() ;
System.exit(1) ;
message = decrypt.toString() ;
message = "re: " + message + "\n" ;
showOnBox.update() ;
}The other side i send is a message with encrypting, so it'll be a list of bye (byte[]),
but it convert to string when receiving this encrypted message....
i need its original "byte[]" data for decrypting....
Can somebody understand my words and help me ?And don't use String, or Reader, or readLine, or println(), to cart around encrypted information in the first place. Ciphertext isn't 'text' at all, it is binary data, and String is not a container for binary data, and there is nothing anywhere in Java or anywhere else that says that the round-trip between bytes and chars should work in both directions without data loss.
Us ea byte[] array. Then the entire problem disappears. -
Odd... either iTunes games in the store go away when you own them, or they don't carry Peggle anymore. I mean, yeah I own it, but still what happened I wonder?
Message was edited by: CowboyJMB
Never mind, delete this message, I feel silly I just saw it now.
Message was edited by: CowboyJMBHi
(bye) Byte.MAX_VALUE + 1 == Byte.MIN_VALUE
the above expression is evaluated as true. why is it
so?
according to my understanding 128 is not equals to
-128.0x7F + 1 == 0x80 -
Well, for those of us who received the 90 day extension, everything runs out this Sunday.
Technet has been great, and I am sad to see my subscription retire.
To everyone who provided feedback attempting to have this decision reversed - thankyou, and I hope Microsoft provide a similar product for tech evangelists going forward in the cloud.
We need a similar product that works exclusively in Azure - that's better than the free trials currently offered. It would definitely drive Azure takeup
Cheers!
Thanks! JoshHi
(bye) Byte.MAX_VALUE + 1 == Byte.MIN_VALUE
the above expression is evaluated as true. why is it
so?
according to my understanding 128 is not equals to
-128.0x7F + 1 == 0x80 -
PackedInteger encoding does not preserve order - but it could
Currently, when viewed under the default unsigned lexical ordering, "packed" integers (and longs) do not sort numerically. This is because for values requiring two or more bytes, the "value" bytes are stored little endian.
For example:
<tt> 65910 -> 7a ff 00 01</tt>
<tt> 65911 -> 7a 00 01 01</tt>
However, it's possible to encode packed integers such that they still sort correctly. You can do this by modifying the existing PackedInteger algorithm as follows:
<li>Invert the high-order bit on the first byte
<li>Reverse the order of the second and subsequent bytes (if any)
<li>If the original number was negative, invert (one's complement) the bits in the second and subsequent bytes (if any)
Here's some examples showing the two encodings:
NUMBER ENCODING NEW ENCODING
-9223372036854775808 8189ffffffffffff7f 018000000000000076
-2147483648 8589ffff7f 0580000076
-65911 86000101 06fefeff
-65910 86ff0001 06feff00
-65655 86000001 06feffff
-65654 87ffff 070000
-65400 8701ff 0700fe
-65399 8700ff 0700ff
-375 870001 07feff
-374 88ff 0800
-120 8801 08fe
-119 89 09
-1 ff 7f
0 00 80
1 01 81
119 77 f7
120 7801 f801
374 78ff f8ff
375 790001 f90100
631 790002 f90200
65399 7900ff f9ff00
65400 7901ff f9ff01
65654 79ffff f9ffff
65655 7a000001 fa010000
65910 7aff0001 fa0100ff
65911 7a000101 fa010100
2147483647 7b88ffff7f fb7fffff88
9223372036854775807 7f88ffffffffffff7f ff7fffffffffffff88So the question is.. any particular reason this wasn't done? Would this alternate encoding be a useful addition? (I'm sure it's not possible to replace the current algorithm at this point).
Thanks.greybird wrote:
Thanks Archie. I appreciate this and I know you have good intentions. Unfortunately, we won't be able to incorporate any code from your svn repository. We can only incorporate submissions if the source code is posted here in our OTN forum.Not a problem... Here is the new class:
package org.dellroad.sidekar.util;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import java.util.Arrays;
* An improved version of Berkeley DB's {@link com.sleepycat.util.PackedInteger} class that packs values in such
* a way that their order is preserved when compared using the default binary unsigned lexical ordering.
* @see <a href="http://forums.oracle.com/forums/thread.jspa?messageID=4126254">Berkeley DB Java Edition forum posting</a>
public final class PackedLong {
* Maximum possible length of an encoded value.
public static final int MAX_ENCODED_LENGTH = 9;
* Minimum value for the first byte of a single byte encoded value. Lower values indicate a multiple byte encoded negative value.
public static final int MIN_SINGLE_BYTE_ENCODED = 0x08; // values 0x00 ... 0x07 prefix negative values
* Maximum value for the first byte of a single byte encoded value. Higher values indicate a multiple byte encoded positive value.
public static final int MAX_SINGLE_BYTE_ENCODED = 0xf7; // values 0xf8 ... 0xff prefix positive values
* Adjustment applied to single byte encoded values before encoding.
public static final int ZERO_ADJUST = 127; // single byte value that represents zero
* Minimum value that can be encoded as a single byte.
public static final int MIN_SINGLE_BYTE_VALUE = MIN_SINGLE_BYTE_ENCODED - ZERO_ADJUST; // -119
* Maximum value that can be encoded as a singel byte.
public static final int MAX_SINGLE_BYTE_VALUE = MAX_SINGLE_BYTE_ENCODED - ZERO_ADJUST; // 120
* Adjustment applied to multiple byte encoded negative values before encoding.
public static final int NEGATIVE_ADJUST = -MIN_SINGLE_BYTE_VALUE; // 119
* Adjustment applied to multiple byte encoded positive values before encoding.
public static final int POSITIVE_ADJUST = -(MAX_SINGLE_BYTE_VALUE + 1); // -121
// Cutoff values at which the encoded length changes (this field is package private for testing purposes)
static final long[] CUTOFF_VALUES = new long[] {
0xff00000000000000L - NEGATIVE_ADJUST, // [ 0] requires 8 bytes
0xffff000000000000L - NEGATIVE_ADJUST, // [ 1] requires 7 bytes
0xffffff0000000000L - NEGATIVE_ADJUST, // [ 2] requires 6 bytes
0xffffffff00000000L - NEGATIVE_ADJUST, // [ 3] requires 5 bytes
0xffffffffff000000L - NEGATIVE_ADJUST, // [ 4] requires 4 bytes
0xffffffffffff0000L - NEGATIVE_ADJUST, // [ 5] requires 3 bytes
0xffffffffffffff00L - NEGATIVE_ADJUST, // [ 6] requires 2 bytes
MIN_SINGLE_BYTE_VALUE, // [ 7] requires 1 byte
MAX_SINGLE_BYTE_VALUE + 1, // [ 8] requires 2 bytes
0x0000000000000100L - POSITIVE_ADJUST, // [ 9] requires 3 bytes
0x0000000000010000L - POSITIVE_ADJUST, // [10] requires 4 bytes
0x0000000001000000L - POSITIVE_ADJUST, // [11] requires 5 bytes
0x0000000100000000L - POSITIVE_ADJUST, // [12] requires 6 bytes
0x0000010000000000L - POSITIVE_ADJUST, // [13] requires 7 bytes
0x0001000000000000L - POSITIVE_ADJUST, // [14] requires 8 bytes
0x0100000000000000L - POSITIVE_ADJUST, // [15] requires 9 bytes
private PackedLong() {
* Write the encoded value to the output.
* @param output destination for the encoded value
* @param value value to encode
public static void write(TupleOutput output, long value) {
output.makeSpace(MAX_ENCODED_LENGTH);
int len = encode(value, output.getBufferBytes(), output.getBufferLength());
output.addSize(len);
* Read and decode a value from the input.
* @param input input holding an encoded value
* @return the decoded value
public static long read(TupleInput input) {
long value = decode(input.getBufferBytes(), input.getBufferOffset());
input.skipFast(getReadLength(input));
return value;
* Determine the length (in bytes) of an encoded value without advancing the input.
* @param input input holding an encoded value
* @return the length of the encoded value
public static int getReadLength(TupleInput input) {
return getReadLength(input.getBufferBytes(), input.getBufferOffset());
* Determine the length (in bytes) of an encoded value.
* @param buf buffer containing encoded value
* @param off starting offset of encoded value
* @return the length of the encoded value
* @throws ArrayIndexOutOfBoundsException if {@code off} is not a valid offset in {@code buf}
public static int getReadLength(byte[] buf, int off) {
int prefix = buf[off] & 0xff;
if (prefix < MIN_SINGLE_BYTE_ENCODED)
return 1 + MIN_SINGLE_BYTE_ENCODED - prefix;
if (prefix > MAX_SINGLE_BYTE_ENCODED)
return 1 + prefix - MAX_SINGLE_BYTE_ENCODED;
return 1;
* Determine the length (in bytes) of the encoded value.
* @return the length of the encoded value, a value between one and {@link #MAX_ENCODED_LENGTH}
public static int getWriteLength(long value) {
int index = Arrays.binarySearch(CUTOFF_VALUES, value);
if (index < 0)
index = ~index - 1;
return index < 8 ? 8 - index : index - 6;
* Encode the given value into a new buffer.
* @param value value to encode
* @return byte array containing the encoded value
public static byte[] encode(long value) {
byte[] buf = new byte[MAX_ENCODED_LENGTH];
int len = encode(value, buf, 0);
if (len != MAX_ENCODED_LENGTH) {
byte[] newbuf = new byte[len];
System.arraycopy(buf, 0, newbuf, 0, len);
buf = newbuf;
return buf;
* Encode the given value and write the encoded bytes into the given buffer.
* @param value value to encode
* @param buf output buffer
* @param off starting offset into output buffer
* @return the number of encoded bytes written
* @throws ArrayIndexOutOfBoundsException if {@code off} is negative or the encoded value exceeds the given buffer
public static int encode(long value, byte[] buf, int off) {
int len = 1;
if (value < MIN_SINGLE_BYTE_VALUE) {
value += NEGATIVE_ADJUST;
long mask = 0x00ffffffffffffffL;
for (int shift = 56; shift != 0; shift -= 8) {
if ((value | mask) != ~0L)
buf[off + len++] = (byte)(value >> shift);
mask >>= 8;
buf[off] = (byte)(MIN_SINGLE_BYTE_ENCODED - len);
} else if (value > MAX_SINGLE_BYTE_VALUE) {
value += POSITIVE_ADJUST;
long mask = 0xff00000000000000L;
for (int shift = 56; shift != 0; shift -= 8) {
if ((value & mask) != 0L)
buf[off + len++] = (byte)(value >> shift);
mask >>= 8;
buf[off] = (byte)(MAX_SINGLE_BYTE_ENCODED + len);
} else {
buf[off] = (byte)(value + ZERO_ADJUST);
return 1;
buf[off + len++] = (byte)value;
return len;
* Decode a value from the given buffer.
* @param buf buffer containing an encoded value
* @param off starting offset of the encoded value in {@code buf}
* @return the decoded value
* @throws ArrayIndexOutOfBoundsException if {@code off} is negative or the encoded value is truncated
* @see #getReadLength
public static long decode(byte[] buf, int off) {
int first = buf[off++] & 0xff;
if (first < MIN_SINGLE_BYTE_ENCODED) {
long value = ~0L;
while (first++ < MIN_SINGLE_BYTE_ENCODED)
value = (value << 8) | (buf[off++] & 0xff);
return value - NEGATIVE_ADJUST;
if (first > MAX_SINGLE_BYTE_ENCODED) {
long value = 0L;
while (first-- > MAX_SINGLE_BYTE_ENCODED)
value = (value << 8) | (buf[off++] & 0xff);
return value - POSITIVE_ADJUST;
return (byte)(first - ZERO_ADJUST);
}and here is the unit test:
package org.dellroad.sidekar.util;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseEntry;
import org.dellroad.sidekar.TestSupport;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class PackedLongTest extends TestSupport {
@Test(dataProvider = "encodings")
public void testEncoding(long value, String string) {
// Test direct encoding
byte[] expected = ByteArrayEncoder.decode(string);
byte[] actual = PackedLong.encode(value);
assertEquals(actual, expected);
// Test write()
TupleOutput out = new TupleOutput();
PackedLong.write(out, value);
assertEquals(out.toByteArray(), expected);
// Test getWriteLength()
assertEquals(actual.length, PackedLong.getWriteLength(value));
// Test decoding
long value2 = PackedLong.decode(actual, 0);
assertEquals(value2, value);
// Test read()
TupleInput input = JEUtil.toTupleInput(new DatabaseEntry(actual));
assertEquals(actual.length, PackedLong.getReadLength(input));
value2 = PackedLong.read(input);
assertEquals(value2, value);
// Test getReadLength()
assertEquals(actual.length, PackedLong.getReadLength(actual, 0));
@Test(dataProvider = "lengths")
public void testEncodedLength(long value, int expected) {
int actual = PackedLong.getWriteLength(value);
assertEquals(actual, expected);
byte[] buf = PackedLong.encode(value);
assertEquals(buf.length, expected);
@DataProvider(name = "encodings")
public Object[][] genEncodings() {
return new Object[][] {
// Corner cases
{ 0x8000000000000000L, "008000000000000077" },
{ 0xfeffffffffffff88L, "00feffffffffffffff" },
{ 0xfeffffffffffff89L, "0100000000000000" },
{ 0xfeffffffffffffffL, "0100000000000076" },
{ 0xfffeffffffffff88L, "01feffffffffffff" },
{ 0xfffeffffffffff89L, "02000000000000" },
{ 0xfffeffffffffffffL, "02000000000076" },
{ 0xfffffeffffffff88L, "02feffffffffff" },
{ 0xfffffeffffffff89L, "030000000000" },
{ 0xfffffeffffffffffL, "030000000076" },
{ 0xfffffffeffffff88L, "03feffffffff" },
{ 0xfffffffeffffff89L, "0400000000" },
{ 0xfffffffeffffffffL, "0400000076" },
{ 0xfffffffffeffff88L, "04feffffff" },
{ 0xfffffffffeffff89L, "05000000" },
{ 0xfffffffffeffffffL, "05000076" },
{ 0xfffffffffffeff88L, "05feffff" },
{ 0xfffffffffffeff89L, "060000" },
{ 0xfffffffffffeffffL, "060076" },
{ 0xfffffffffffffe88L, "06feff" },
{ 0xfffffffffffffe89L, "0700" },
{ 0xfffffffffffffeffL, "0776" },
{ 0xffffffffffffff88L, "07ff" },
{ 0xffffffffffffff89L, "08" },
{ 0xffffffffffffffa9L, "28" },
{ 0xffffffffffffffc9L, "48" },
{ 0xffffffffffffffe9L, "68" },
{ 0xffffffffffffffffL, "7e" },
{ 0x0000000000000000L, "7f" },
{ 0x0000000000000001L, "80" },
{ 0x0000000000000071L, "f0" },
{ 0x0000000000000077L, "f6" },
{ 0x0000000000000078L, "f7" },
{ 0x0000000000000079L, "f800" },
{ 0x0000000000000178L, "f8ff" },
{ 0x0000000000000179L, "f90100" },
{ 0x0000000000010078L, "f9ffff" },
{ 0x0000000000010079L, "fa010000" },
{ 0x0000000001000078L, "faffffff" },
{ 0x0000000001000079L, "fb01000000" },
{ 0x0000000100000078L, "fbffffffff" },
{ 0x0000000100000079L, "fc0100000000" },
{ 0x0000010000000078L, "fcffffffffff" },
{ 0x0000010000000079L, "fd010000000000" },
{ 0x0001000000000078L, "fdffffffffffff" },
{ 0x0001000000000079L, "fe01000000000000" },
{ 0x0100000000000078L, "feffffffffffffff" },
{ 0x0100000000000079L, "ff0100000000000000" },
{ 0x7fffffffffffff79L, "ff7fffffffffffff00" },
{ 0x7fffffffffffffffL, "ff7fffffffffffff86" },
// Other cases
{ 0xffffffff80000000L, "0480000077" },
{ 0xfffffffffffefe89L, "05feff00" },
{ 0xfffffffffffefe8aL, "05feff01" },
{ 0xfffffffffffeff86L, "05fefffd" },
{ 0xfffffffffffeff87L, "05fefffe" },
{ 0xfffffffffffeff88L, "05feffff" },
{ 0xfffffffffffeff89L, "060000" },
{ 0xfffffffffffeff8aL, "060001" },
{ 0xffffffffffff0086L, "0600fd" },
{ 0xffffffffffff0087L, "0600fe" },
{ 0xffffffffffff0088L, "0600ff" },
{ 0xffffffffffff0089L, "060100" },
{ 0xfffffffffffffe86L, "06fefd" },
{ 0xfffffffffffffe87L, "06fefe" },
{ 0xfffffffffffffe89L, "0700" },
{ 0xfffffffffffffe8aL, "0701" },
{ 0xffffffffffffff87L, "07fe" },
{ 0xffffffffffffff88L, "07ff" },
{ 0xffffffffffffff89L, "08" },
{ 0xffffffffffffffffL, "7e" },
{ 0x0000000000000000L, "7f" },
{ 0x0000000000000001L, "80" },
{ 0x0000000000000077L, "f6" },
{ 0x0000000000000078L, "f7" },
{ 0x0000000000000176L, "f8fd" },
{ 0x0000000000000177L, "f8fe" },
{ 0x0000000000000178L, "f8ff" },
{ 0x0000000000000277L, "f901fe" },
{ 0x000000000000ff77L, "f9fefe" },
{ 0x000000000000ff78L, "f9feff" },
{ 0x000000000000ff79L, "f9ff00" },
{ 0x000000000000ff7aL, "f9ff01" },
{ 0x0000000000010076L, "f9fffd" },
{ 0x0000000000010077L, "f9fffe" },
{ 0x0000000000010078L, "f9ffff" },
{ 0x0000000000010079L, "fa010000" },
{ 0x000000000001007aL, "fa010001" },
{ 0x0000000000010176L, "fa0100fd" },
{ 0x0000000000010177L, "fa0100fe" },
{ 0x000000007fffffffL, "fb7fffff86" },
{ 0x7fffffffffffffffL, "ff7fffffffffffff86" },
@DataProvider(name = "lengths")
public Object[][] genLengths() {
return new Object[][] {
// Check cutoff values
{ PackedLong.CUTOFF_VALUES[ 0] - 1, 9 },
{ PackedLong.CUTOFF_VALUES[ 0], 8 },
{ PackedLong.CUTOFF_VALUES[ 1] - 1, 8 },
{ PackedLong.CUTOFF_VALUES[ 1], 7 },
{ PackedLong.CUTOFF_VALUES[ 2] - 1, 7 },
{ PackedLong.CUTOFF_VALUES[ 2], 6 },
{ PackedLong.CUTOFF_VALUES[ 3] - 1, 6 },
{ PackedLong.CUTOFF_VALUES[ 3], 5 },
{ PackedLong.CUTOFF_VALUES[ 4] - 1, 5 },
{ PackedLong.CUTOFF_VALUES[ 4], 4 },
{ PackedLong.CUTOFF_VALUES[ 5] - 1, 4 },
{ PackedLong.CUTOFF_VALUES[ 5], 3 },
{ PackedLong.CUTOFF_VALUES[ 6] - 1, 3 },
{ PackedLong.CUTOFF_VALUES[ 6], 2 },
{ PackedLong.CUTOFF_VALUES[ 7] - 1, 2 },
{ PackedLong.CUTOFF_VALUES[ 7], 1 },
{ PackedLong.CUTOFF_VALUES[ 8] - 1, 1 },
{ PackedLong.CUTOFF_VALUES[ 8], 2 },
{ PackedLong.CUTOFF_VALUES[ 9] - 1, 2 },
{ PackedLong.CUTOFF_VALUES[ 9], 3 },
{ PackedLong.CUTOFF_VALUES[10] - 1, 3 },
{ PackedLong.CUTOFF_VALUES[10], 4 },
{ PackedLong.CUTOFF_VALUES[11] - 1, 4 },
{ PackedLong.CUTOFF_VALUES[11], 5 },
{ PackedLong.CUTOFF_VALUES[12] - 1, 5 },
{ PackedLong.CUTOFF_VALUES[12], 6 },
{ PackedLong.CUTOFF_VALUES[13] - 1, 6 },
{ PackedLong.CUTOFF_VALUES[13], 7 },
{ PackedLong.CUTOFF_VALUES[14] - 1, 7 },
{ PackedLong.CUTOFF_VALUES[14], 8 },
{ PackedLong.CUTOFF_VALUES[15] - 1, 8 },
{ PackedLong.CUTOFF_VALUES[15], 9 },
// Check some other values
{ Long.MIN_VALUE, 9 },
{ Long.MAX_VALUE, 9 },
{ (long)Integer.MIN_VALUE, 5 },
{ (long)Integer.MAX_VALUE, 5 },
{ (long)Short.MIN_VALUE, 3 },
{ (long)Short.MAX_VALUE, 3 },
{ (long)Byte.MIN_VALUE, 2 },
{ (long)Byte.MAX_VALUE, 2 },
{ 0, 1 },
}Edited by: archie172 on Mar 3, 2010 12:40 PM
Removed copyright message. -
Integer.parseInt problems
Hi everyone,
I want to use the Integer.parseInt and Byte.parseByte methods to parse hex strings - the problem is that they don't parse negative 2's complement numbers, they explicitly need a minus sign in front of an otherwise unsigned number to show that it's negative.
Examples:
//System.out.println(Integer.parseInt(Integer.toHexString(-1), 16)); //NumberFormatException
System.out.println(0xffffffff); // but this prints -1
//System.out.println(Byte.parseByte("ff", 16)); //NumberFormatException
System.out.println(Byte.parseByte("-1", 16)); // but this worksIs there some other method that will do what I need?
Regards,
JonathanHere's a dirty solution:public class Test {
private static char[] digits = new char[] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
public static void main (String[] parameters) {
String number = Integer.toHexString (parameters[0].equals ("+") ? Integer.MAX_VALUE : parameters[0].equals ("-") ? Integer.MIN_VALUE : Integer.parseInt (parameters[0]));
if ((number.length () == 8) && (getPosition (number.charAt (0)) >= 8)) {
String newNumber = "";
for (int i = 0; i < number.length (); i ++) {
newNumber += digits[15 - getPosition (number.charAt (i))];
number = "";
boolean carry = true;
for (int i = 7; i >= 0; i --) {
int position = getPosition (newNumber.charAt (i));
if (carry) {
position = (position + 1) % 16;
carry = (position == 0);
number = digits[position] + number;
number = "-" + number;
int numberAsInt;
try {
numberAsInt = Integer.parseInt (number, 16);
} catch (NumberFormatException exception) {
// -8000000
numberAsInt = Integer.MIN_VALUE;
System.out.println (numberAsInt);
private static int getPosition (char digit) {
int position = 0;
while ((position < digits.length) && (digits[position] != digit)) {
position ++;
return position;
}Start with java Test <yourNumber>: + for Integer.MAX_VALUE, - for Integer.MIN_VALUE.
I don't claim it's good or efficient: it's working though. There's lots of things to improve.
Kind regards,
Levi -
Hello again
I have just written this code
import java.awt.*;
import java.applet.*;
public class DataTypes extends Applet {
//paint on the applet window
public void paint(Graphics g) {
//select a nice font
g.setFont(new Font("Courier New", Font.PLAIN, 12));
//display minimum and maximum values for the numeric data types
g.drawString("Byte : " + Byte.MIN_VALUE + " to " + Byte.Max_VALUE, 5, 20);
g.drawString("Short : " + Short.MIN_VALUE + " to " + Short.Max_VALUE, 5, 35);
g.drawString("Integer : " + Integer.MIN_VALUE + " to " + Integer.Max_VALUE, 5, 50);
g.drawString("Long : " + Long.MIN_VALUE + " to " + Long.Max_VALUE, 5, 65);
g.drawString("Float : " + Float.MIN_VALUE + " to " + Float.Max_VALUE, 5, 80);
g.drawString("Double : " + Double.MIN_VALUE + " to " + Double.MAX_VALUE, 5, 95);
} When i went to go and compile it with the command prompt, it comes up with 6 errors saying "variable MAX_VALUE" with a arrow facing upwards towards all of the dots before "MAX_Value"
please helpMAX_VALUE not Max_VALUE.
-
Collisions (Separating Axis Theorem)
Hi,
I'm working on a 2D game, it's top-down like GTA2, but I'm havinfgproblems with the collision detector. I know there are a lot of posts about collision already but they didn't help me much. I'm using the separating axis theorem (explained here: http://www.harveycartel.org/metanet/tutorials/tutorialA.html#section1) and most of the code is inspired by http://www.codeproject.com/cs/media/PolygonCollision.asp .
Separating axis theorem:
find all axis perpendicular to all the edges of both objects,
project both objects on the axis,
if there is an axis where the projections do not overlap, then the objects do not overlap.
The problem is that I think my code should work. And guess what, it doesn't. I checked the code 30 times this weekend but maybe there is some tiny mistake I overlook each time..
When I run the program with 6 objects I get this:
1 2 3 4 5 6
1: - 0 0 0 0 0
2: 0 - 1 0 0 0
3: 0 1 - 0 0 0
4: 0 0 0 - 0 0
5: 0 0 0 0 - 0
6: 0 0 0 0 0 - (1=intersect, 0=doesn't intersect)
but this is completely wrong. You can run the program yourself to see the exact locations of the objects.
1 is the triangle at the top,
2 and 3 are the triangles who share an edge
4 is the one on the left intersecting with 3
5 is the triangle on the right
6 is the parallelogram
But it really gets weird when I add a 7th object (the one in the comments):
1 2 3 4 5 6 7
1: - 0 0 0 0 0 0
2: 0 - 0 0 0 0 0
3: 0 0 - 0 0 0 0
4: 0 0 0 - 0 0 0
5: 0 0 0 0 - 0 0
6: 0 0 0 0 0 - 0
7: 0 0 0 0 0 0 -
Now 2 and 3 don't intersect anymore! They didn't change I just added another object.
I'm adding a short explanationof all the classes and the code itself. I know it's a lot of code but I added all the test classes so you can just run Test.Test
I hope someone can help me with this.
Thanks,
El Bandano
_<h5>package CollisionDetector:</h5>_
<h6>CollisionDetector</h6>
The class that is supposed to check for collisions. It will take 2 Props and return a CollisionResult
<h6>CollisionResult</h6>
A small class with 2 public fields. For now only the boolean Intersect matters.
<h6>Interval</h6>
Another small class that represents an interval of floats. It's pretty simple. Distance should return something negative if 2 intervals overlap.
_<h5>package World</h5>_
<h6>MovableProp</h6>
An interface of an object. All objects should be convex.
<h6>Vector2D</h6>
A 2D-vector. It has an x and a y value (floats) and some simple methods. a 2D vector can represent a point or an edge/axis. For a point the x and y are the coordinates. For an axis you need a normalized vector (x^2+y^2=1) and the x and y are coordinates on a parrallell line through (0,0).
_<h5>package Test</h5>_
<h6>Test</h6>
The main class. It makes some objects, prints a matrix showin which intersect eachother and shows a window with all objects.
<h6>TestMovProp</h6>
A basic implementation of MovableProp.
<h6>TestPanel</h6>
A panel that draws MovableProp.
_<h5>package CollisionDetector:</h5>_
<h6>CollisionDetector</h6>
package CollsisionDetector;
import World.MovableProp;
import World.Vector2D;
import java.util.ArrayList;
public class CollisionDetector {
public CollisionDetector(){
public CollisionResult DetectCollision(MovableProp propA, MovableProp propB) {
CollisionResult result = new CollisionResult();
result.Intersect = true;
result.WillIntersect = true;
Vector2D[] edges = UniqueEdges(propA, propB);
// loop through the edges
// find an axis perpendicular to the edge
// project the props on the axis
// check wether they intersect on that axis
for (Vector2D edge: edges){
Vector2D axis = edge.getPerpendicular();
Interval intA = projectPointsOnAxis(propA.getCoordinates(), axis);
Interval intB = projectPointsOnAxis(propB.getCoordinates(), axis);
if (intA.distance(intB) > 0)
result.Intersect = false;
return result;
public Interval projectPointsOnAxis(Vector2D[] points, Vector2D axis){
Interval i = new Interval();
for (Vector2D p: points)
i.add(projectPointOnAxis(p, axis));
return i;
public float projectPointOnAxis(Vector2D point, Vector2D axis){
// axis <-> y=a*x
float a = axis.y / axis.x;
// line <-> y=(-a/1)*x+b
float a2 = -axis.x / axis.y;
// b = y-a2*x
float b = point.y - a2*point.x;
// y = a *x
// y = a2*x + b
// => a*x = a2*x + b
float x = b/(a-a2);
float y = a*x;
// is there a better way to do this?
return new Float(Math.sqrt(x*x + y*y)).floatValue();
* Put all edges in 1 array, eliminate doubles (parallels).
public Vector2D[] UniqueEdges(MovableProp propA,MovableProp propB){
Vector2D[] aEdges = propA.getEdges();
Vector2D[] bEdges = propB.getEdges();
ArrayList<Vector2D> tmp = new ArrayList<Vector2D>();
for (Vector2D v: aEdges){
tmp.add(v);
for (Vector2D v: bEdges){
if (! tmp.contains(v))
tmp.add(v);
return tmp.toArray(new Vector2D[tmp.size()]);
}<h6>CollisionResult</h6>
package CollsisionDetector;
import World.Vector2D;
public class CollisionResult {
public boolean WillIntersect;
public boolean Intersect;
public Vector2D MinimumTranslationVector;
public CollisionResult() {
}<h6>Interval</h6>
package CollsisionDetector;
public class Interval {
public float min;
public float max;
public Interval() {
min = Float.MAX_VALUE;
max = Float.MIN_VALUE;
public void add(float f){
// no 'else'! In an empty interval both will be true
if (f>max)
max = f;
if (f<min)
min = f;
public float distance(Interval interval){
if (this.min < interval.min) {
return interval.min - this.min;
} else {
return this.min - interval.min;
}_<h5>package World</h5>_
<h6>MovableProp</h6>
package World;
public interface MovableProp {
public int getNPoints();
public Vector2D[] getEdges();
public Vector2D[] getCoordinates();
}<h6>Vector2D</h6>
package World;
public class Vector2D {
public float x;
public float y;
public Vector2D(float x, float y) {
this.x = x;
this.y = y;
public boolean equals(Object obj){
if (!(obj instanceof Vector2D)){
return false;
}else
return (this.x == ((Vector2D)obj).x && this.y == ((Vector2D)obj).y);
public String toString() {
return ("Vector2D x=" + x + " , y=" + y);
public void normalize(){
if (x*x + y*y != 1){
float x2 = x;
x /= Math.sqrt(x2*x2+y*y);
y /= Math.sqrt(x2*x2+y*y);
public Vector2D getPerpendicular(){
Vector2D per = new Vector2D(-y,x);
per.normalize();
return per;
}_<h5>package Test</h5>_
<h6>Test</h6>
package Test;
import CollsisionDetector.CollisionDetector;
import World.MovableProp;
import java.awt.Polygon;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
public class Test {
public static void main(String args[]) {
CollisionDetector detect = new CollisionDetector();
float[] x = new float[3];
float[] y = new float[3];
ArrayList<MovableProp> list = new ArrayList<MovableProp>();
x[0] = 200; x[1] = 300; x[2] = 500;
y[0] = 400; y[1] = 200; y[2] = 300;
list.add(new TestMovProp(x,y));
x[0] = 300; x[1] = 500; x[2] = 600;
y[0] = 400; y[1] = 400; y[2] = 500;
list.add(new TestMovProp(x,y));
x[0] = 200; x[1] = 300; x[2] = 600;
y[0] = 600; y[1] = 400; y[2] = 500;
list.add(new TestMovProp(x,y));
x[0] = 100; x[1] = 200; x[2] = 300;
y[0] = 800; y[1] = 500; y[2] = 700;
list.add(new TestMovProp(x,y));
x[0] = 600; x[1] = 600; x[2] = 700;
y[0] = 400; y[1] = 700; y[2] = 500;
list.add(new TestMovProp(x,y));
// x[0] = 100; x[1] = 001; x[2] = 900;
// y[0] = 001; y[1] = 900; y[2] = 500;
// list.add(new TestMovProp(x,y));
x = new float[4];
y = new float[4];
x[0] = 450; x[1] = 550; x[2] = 500; x[3] = 400;
y[0] = 200; y[1] = 250; y[2] = 650; y[3] = 600;
list.add(new TestMovProp(x,y));
int n = list.size();
boolean[][] matrix = new boolean[n][n];
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
if (i!=j)
matrix[i][j] = detect.DetectCollision(list.get(i),list.get(j)).Intersect;
System.out.print(" ");
for (int i=0; i<n; i++){
System.out.print(" " + (i+1));
for (int i=0; i<n; i++){
System.out.print("\n" + (i+1) + ": ");
for (int j=0; j<n; j++){
if (i==j)
System.out.print("- ");
else if (matrix[i][j])
System.out.print("1 ");
else
System.out.print("0 ");
System.out.println();
JFrame window = new JFrame();
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
window.setContentPane( new TestPanel(list));
window.pack();
}<h6>TestMovProp</h6>
package Test;
import World.MovableProp;
import World.Vector2D;
public class TestMovProp implements MovableProp{
float[] X;
float[] Y;
Vector2D[] coor;
public TestMovProp(float[] x, float[] y) {
X=x; Y=y;
coor = new Vector2D[getNPoints()];
for(int i=0; i< getNPoints(); i++){
coor[i] = new Vector2D(X, Y[i]);
public Vector2D[] getCoordinates(){
return coor;
public int getNPoints() {
return X.length;
public Vector2D[] getEdges() {
int n = getNPoints();
Vector2D[] v = new Vector2D[n];
for (int i=0; i<n-1; i++){
v[i] = new Vector2D(X[i]-X[i+1], Y[i]-Y[i+1]);
v[i].normalize();
v[n-1] = new Vector2D(X[0]-X[n-1], Y[0]-Y[n-1]);
v[n-1].normalize();
return v;
public String toString() {
String s = "\n";
for (Vector2D v: getCoordinates())
s += ("\n" + v);
return s;
<h6>TestPanel</h6>package Test;
import World.MovableProp;
import World.Vector2D;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.util.ArrayList;
import javax.swing.JPanel;
public class TestPanel extends JPanel {
public ArrayList<MovableProp> list;
public TestPanel(ArrayList<MovableProp> list) {
super();
this.list = list;
setPreferredSize(new Dimension(1000,850));
public void paint(Graphics g) {
super.paint(g);
for (MovableProp prop:list){
Vector2D[] coor = prop.getCoordinates();
int n = prop.getNPoints();
g.drawLine((int)coor[0].x, (int)coor[0].y, (int)coor[n-1].x, (int)coor[n-1].y);
for (int i=0; i<n-1; i++){
g.drawLine((int)coor[i].x, (int)coor[i].y, (int)coor[i+1].x, (int)coor[i+1].y);.java wrote:
I have been search for what seems like hours, Nice try, but in less than 15 seconds I found a complete discussion on the subject.
and I still have not managed to find anybody or anything that can clearly answer these three questions:
1. What is SAT?
2. How does it apply to 2D collision detection? (How would it be different with 3D collision detection?)
3. How can this be implemented in Java using Shape objects?
Note: I am easily confused by geometric terminology.This really looks like a question you should have an answer for in your notes from class, or in your book. If not perhaps you need to go ask your teacher what it is and explain why you don't have it in your notes or book. -
Floating-point numbers: min value
Hi,
the number wrapper classes each define a MAX_VALUE and a MIN_VALUE constant. While the MIN_VALUE of non-floating point numbers are negative numbers, the MIN_VALUE of the floating point numbers are the smallest postive numbers.
From the Javadoc:
Float:
MAX_VALUE:
A constant holding the largest positive finite value of type float, (2-2-23)�2127. It is equal to the hexadecimal floating-point literal 0x1.fffffeP+127f and also equal to Float.intBitsToFloat(0x7f7fffff).
MIN_VALUE:
A constant holding the smallest positive nonzero value of type float, 2-149. It is equal to the hexadecimal floating-point literal 0x0.000002P-126f and also equal to Float.intBitsToFloat(0x1).
MAX_VALUE:
A constant holding the largest positive finite value of type double, (2-2-52)�21023. It is equal to the hexadecimal floating-point literal 0x1.fffffffffffffP+1023 and also equal to Double.longBitsToDouble(0x7fefffffffffffffL).
MIN_VALUE:
A constant holding the smallest positive nonzero value of type double, 2-1074. It is equal to the hexadecimal floating-point literal 0x0.0000000000001P-1022 and also equal to Double.longBitsToDouble(0x1L).
Can someone tell me the MAX_NEGATIVE_VALUE (the finite negative value with the largest absolute value) and the MIN_NEGATIVE_VALUE (the negative value with the smallest nonzero absolute value) of float and double (using the xxxBitsToXxx-methods)?
Thanks!
-PuceThe IEEE754 format is symmetric with respect to the sign, so -MAX_VALUE
and -MIN_VALUE are the values you're looking for.
kind regards,
Jos -
How to set checkbox to fill max or min value in field
Hi all,
I am pretty new to the adobe acrobat and I just created my first pdf form. I would ask for a help:
In this form I have 2 fields where in one is price with VAT and in other without VAT. I also have a check box and total price field in form.
I would like to set this form in a way that if check box is checked price with VAT is copied in the total price field and if check box is unchecked the price without VAT would be copied in the total price field.
My idea is to set the checkbox to copy max value to total price field if checked and min if unchecked. Is there a way to do that? Is there a better way to achieve that?
Thanks for sour help, I appreciate it!
Luka
(I am not familiar with Java)You can set the min/max to int.MIN_VALUE/int.MAX_VALUE or
Number.MIN_VALUE/Number.MAX_VALUE
It isn't unbounded, but will hopefully meet your needs. -
Context switching / Threads
Hello !
The following program is for 3 Threads which do context switching.
Often we get '0' zero for the low priority thread when we run this program.
MY QUESTION IS WHY DO WE GET ZERO ?
As far as my understanding is concerned; even if preemptive multitasking is done by the threads,
the low priority thread should have run through few iterations and thus giving some value other
than zero '0'.
Secondly most of the time we get negative values for the high priority thread. Why is that ?
Is it because of the fact that volatile sets the variable 'running' to some different value ?
The speed of my processor is 1.5GHz.
GOD BLESS YOU.
NADEEM.
// Demonstrates threads priorities.
class Clicker implements Runnable {
int click = 0;
String name ;
Thread t ;
private boolean running = true ;
public Clicker(String tname, int p) {
name = tname ;
t = new Thread(this, name);
t.setPriority(p);
System.out.println("Current Thread is " + t + " " + t.getPriority());
public void start() {
t.start();
public void run() {
while (running) {
click++;
public void stop() {
running = false ;
class HLPriority {
public static void main(String args[]) {
System.out.println("Active Count : " + Thread.activeCount());
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Clicker hi = new Clicker("Hi", Thread.NORM_PRIORITY + 2);
Clicker lo = new Clicker("Lo", Thread.NORM_PRIORITY - 2);
System.out.println("Active Count : " + Thread.activeCount());
lo.start();
hi.start();
try {
System.out.println("Sleeping Thread : " + Thread.currentThread());
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted : " + e);
hi.stop();
lo.stop();
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception caught : " + e);
System.out.println("Low priority thread : " + lo.click);
System.out.println("Hi priority thread : " + hi.click);
}Hello !
The following program is for 3 Threads which do
context switching.
Often we get '0' zero for the low priority thread when
we run this program.
MY QUESTION IS WHY DO WE GET ZERO ?Presumably because the low priority thread gets no CPU time.
>
As far as my understanding is concerned; even if
preemptive multitasking is done by the threads,
the low priority thread should have run through few
iterations and thus giving some value other
than zero '0'.You can't make ANY assumptions about when or how much CPU time a given thread will get. Why don't you let your main thread sleep longer--a minute or 5 or ten--and see if LO gets some cycles then.
Secondly most of the time we get negative values for
the high priority thread. Why is that ?count = Integer.MAX_VALUE;
count++; // --> Integer.MIN_VALUE (-2^31)
I guess 10 seconds is enough time for a thread in a tight loop to count to 2 billion.
Is it because of the fact that volatile sets the
variable 'running' to some different value ?Volatile does nothing of the sort, and, in any case, isn't even in your code.
GOD BLESS YOU.I didn't sneeze. -
Help trying to convert string to int
Hey im trying to input a string in an applet then turn it into a integer so i can use it any ideas?
long val = Long.parseLong(string);
if(val > Integer.MAX_VALUE || val <
Integer.MIN_VALUE) {
throw new Error("I don't like you :p");
int intVal = (int) val;No real need to use parseLong and check explicitly the limits. The check for MIN and MAX is performed implicitely inside Integer.parseInt(string, 10), which is called by both new Integer(string).intValue() and Integer.parseInt(string) . When the check fails, it throws a NumberFormatException.
The only difference between post#1 and post#2 is that the latter it stores the int value in the internal int data member after the call to Integer.parseInt(string, 10), hence the intValue() subsequent call. -
i have this query:
select XMLELEMENT(name "eeml",
XMLAGG(XMLELEMENT(name "environment",XMLCONCAT(
XMLELEMENT(name "title", a.codice),
XMLELEMENT(name "data", XMLATTRIBUTES(x.data_id as "id"),
XMLCONCAT(XMLELEMENT(name "tag", x.tag),
XMLELEMENT(name "datapoints",
(XMLELEMENT(name "value",round(avg(x.avg_data),2)))
XMLELEMENT(name "unit", x.unit)
as xml
from ambiente a, table(a.dati) d, XMLTABLE('for $d in //data return <dati>
<id>{data($d/@id)}</id>
<tag>{$d/tag}</tag>
<unit>{$d/unit}</unit>
<avg>{(data($d/max_value)+data($d/min_value)) div 2}</avg>
</dati>' PASSING value(d).DatiXML
COLUMNS data_id integer PATH '/dati/id',
tag varchar2(20) PATH '/dati/tag',
unit varchar2(20) PATH '/dati/unit',
avg_data number(5) PATH '/dati/avg'
) x
where to_char(value(d).giorno,'YYYY')='2011'
group by a.codice,x.data_id,x.tag,x.unit, to_char(value(d).giorno,'MON')
order by x.data_id
that produce:
<eeml>
<environment>
<title>1</title>
<data id="2">
<tag>temperature</tag>
<datapoints>
<value>36</value> //avg january value
</datapoints>
<unit>Celsius</unit>
</data>
</environment>
<environment>
<title>1</title>
<data id="0">
<tag>energy</tag>
<datapoints>
<value>38.5</value> //avg january value
</datapoints>
<unit>Kilowatt</unit>
</data>
</environment>
<environment>
<title>1</title>
<data id="2">
<tag>temperature</tag>
<datapoints>
<value>36</value> //avg february value
</datapoints>
<unit>Celsius</unit>
</data>
</environment>
<environment>
<title>1</title>
<data id="0">
<tag>energy</tag>
<datapoints>
<value>36</value> //avg february value
</datapoints>
<unit>Kilowatthour</unit>
</data>
</environment>
</eeml>
but i want to have
<eeml>
<environment>
<title>1</title>
<data id="2">
<tag>temperature</tag>
<datapoints>
<value>36</value> //avg january
<value>36</value> //avg february
</datapoints>
<unit>Celsius</unit>
</data>
<data id="0">
<tag>energy</tag>
<datapoints>
<value>38.5</value> //avg january
<value>36</value> //avg february
</datapoints>
<unit>Kilowatt</unit>
</data>
</environment>
</eeml>
i have tried to put a xmlagg before the xmlconcat but doesn't work. What is the solution? Thanks for helpingDifficult to tell exactly just from the query. Have you tried changing...
XMLAGG(x.extractedcode)
to
XMLAGG(XMLELEMENT("tagname", x.extractedcode))
P.S. You may be better asking XML type questions on the XMLDB forum for which the FAQ thread is here: XML DB FAQ
Message was edited by:
blushadow
Maybe you are looking for
-
Dear All, Please provide me with the standard cash advance report for Travel management. Regards, Raziq
-
Lion + Finder : How to empty Trash ?
Problem context: OS X Lion Developer environment (involved: git, Titanium Studio) Sounds like filesystem corruption What happens: When I try to empty the trash, a preparation window appears, with an activity indicator (preparing to delete) and it nev
-
I'm new to the mac world...I just got my mac before Christmas. Everything has been going fine until this morning. I was working on making a calendar in iphoto when iphoto just suddenly froze. It won't let me quit the program or anything. Hopefully th
-
About a year ago I had to buy a new battery for my MacBook because the one I had had expanded so horribly it was causing the computer to not function properly. Apple refused to to help and I had to pay full price for the new battery. Now the replacem
-
ATG publishing(asset management), staging, production topology configuration
I want to configure atg publishing, staging and production databases/datasources and servers for a typical atg commerce site. I do not want to use CIM tool to do the same. Hence, can anyone tell me what are the sql scripts to run on PUBLISHING(Asset