Archived

This topic is now archived and is closed to further replies.

java bitwise operator !!

This topic is 5886 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i''m at school and i need to write a function in java that takes an int and return the negativ or the positiv depending on the sign of the int. of course without using the minus sign !! ex. -5 becomes 5 and 5 becomes -5 that''s my solution private int PosNeg( int n) { n = ~n + 1; return n; } is that correct ? is there a better solution ? thanks

Share this post


Link to post
Share on other sites
I don''t know java very well, so what you posted makes no sense at all to me. I know that if I was going to do this _without_ bitwise operators, I would do it like this:

n -= 2*n;

In C and C++, you could also use a bitshift to make it go faster:

n -= n << 1;

Like I said, I know little about java, so I don''t know if those are portable solutions.

--------------------


You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming

You are unique. Just like everybody else.

"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor

Yanroy@usa.com

Share this post


Link to post
Share on other sites
quote:
Original post by Yanroy
I don''t know java very well, so what you posted makes no sense at all to me. I know that if I was going to do this _without_ bitwise operators, I would do it like this:

n -= 2*n;



That''s not very good - what about when you pass it 0x7FFFFFFF? That should be converted to 0xFFFFFFFF, but since your solution would overflow in the 2*n bit, you''d return some funny number...

The ''~'' operator is bitwise-NOT. That is, it''ll invert every bit in a number. To negate a number in 2''s compliment, you invert the bits and add 1. i.e., n = ~n + 1


codeka.com - Just click it.

Share this post


Link to post
Share on other sites
I never said my solution was perfect, I just said it''s what I would do. I would never end up passing it a number that large If I had known java''s bitwise operators, I would have suggested the inversion thingy... I do it all the time on the pathetic little one-board computers I use in my robots

--------------------


You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming

You are unique. Just like everybody else.

"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor

Yanroy@usa.com

Share this post


Link to post
Share on other sites