Why do I receive a -1 when reading a bit field?

  • Thread starter Thread starter BB
  • Start date Start date
B

BB

Hello,

I retrieve a SQL Server 2000 table into a local Dataset. Whenever I retrieve
data from a bit field if the value is 1 in table column, the return value I
receive is -1. A 0 in the table always returns a 0. Why is this?

Thanks!
Bob
 
Hi BB,

What is the column's DataType?
If it is boolean you should get true and false.
Even if it is a numeric type you should get 1 and 0.
What is the command's CommandText?
 
Hi Bob

This is probably intentional behaviour... -1 = true, 0=false when more than
1 bit is used to represent booleans, which may the case for you. The reason
is, that the inverse of true must be false (obviously). So if false is
0000...etc, then true must be 1111.... In binary, 1111...etc represents the
signed integer -1, which answers your question.
Incidently, if true were 1, = 0000...001, then false would be 1111...110
= -2, which would make even less sense :-)

Anyway, in c# and vb.net you can't substitute 0/1 for false/true the way
it's done in c/c++. It's a pain, but makes the code more readable.

-- and if you wonder why 11111... = -1, try doing math with the following
without paying attention to signs:
Consider only 3 bit signed integers. 000 = 0, 001 = 1, 010 = 2, 011 = 3, 100
= -4, 101 = -3, 110 = -2, 111 = -1. Do some math and you'll notice that you
don't have to consider signs when implementing addition, subtraction and
multiplication. If you have an overflow, you end up with a negative integer.
It also explains why the ranges of numbers vary between -x and x-1 (ie. -128
to 127 for 8 bit signed integers)

Mikkel
 
Thanks, Miha.

You nailed it!! I found a variable of Integer type holding that bit data
from the SQL database column. I changed the Integer to Boolean for the
variable and True/False started working well.

Regards,
Bob
 
Back
Top