1

I have a binary string as follows:

String bin = "1101";

and I want my int's value to be -3 instead of 13

What is the best way to achieve this?

2
  • Are you assuming that every string with a leading 1 is negative? Would 13 have to be represented as "01101"? Or have you got a fixed size of 4 bits? More details required, basically. Commented May 9, 2012 at 8:50
  • 1
    Long res = Long.parseLong(bin, 2); if (bin.charAt(0)=='1' && bin.length()==n) res -= (1L<<n); Commented May 9, 2012 at 9:49

1 Answer 1

6

Use if (i >= k) i -= 2 * k; Where k is the smallest positive number your scheme cannot represent. (8 in this case, because 0111 is 7 and 1000 would be negative.)

13 is greater than 8, so you'd subtract 16 from 13, giving -3.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.