Convert binary string to signed integer like "1111 1111 1" to signed int in case of larger binary length

Vivek Kumar 21 Reputation points
2021-09-15T10:00:36.827+00:00

Convert binary string to signed integer like "1111 1111 1" to signed int in case of larger binary length

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-09-15T10:35:05.577+00:00

    Before you give more details, try an example:

    string example = "-1011 1";
    int sign = example.StartsWith( "-" ) ? -1 : +1;
    int result = sign * Convert.ToInt32( example.TrimStart( '-', '+' ).Replace( " ", "" ), 2 );
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.