Interesting problem comparing strings with integer values...

Chad Netzer cnetzer at mail.arc.nasa.gov
Wed Jan 15 20:56:04 EST 2003


On Wednesday 15 January 2003 16:19, Chris Spencer wrote:
> The comparison will not be done inside of a Python interpreter,
> but in an SQL statement.
[snip]

At least a HINT to that effect in your original post would have saved 
me and others from wasting our time in this Python forum, thinking up 
and posting Python answers to your non-Python question.

That said, I know nothing of SQL, or SQL datatypes, etc.  How IS this 
related to Python?  Are you using Python to generate the data form 
inclusion in a databse, perhaps?  Are the SQL queries being controlled 
by a python program, etc. etc.?


> Note that this works as well:
> select blah from table where value>"1111100111" and
> value<"110101101000";

Again, I know nothing of SQL, but if you are doing a straightforward 
lexicographical comparison here, this doesn't make sense.  These 
values, if they are thought of as binary strings, are NOT ordered by 
numerical value.

For example, in Python (or any other common language with string 
compare, that I know of), the first value is considered to be GREATER 
than the second, ven though numerically it is clearly smaller, ie.:

Python 2.2.2 (#1, Jan  3 2003, 12:42:27) 
>>> a = "1111100111"
>>> b = "110101101000"
>>> a > b
1

Now, if things are different in SQL, then that is that.  But I could 
only suggest that this is not the right newsgroup to discuss the issue 
(despite most of the posters being nice, friendly people; of which I 
must right now seem the exception)

> However, I've not been able to find an equivalent to hex() or oct()
> that would turn integers into binary string representation.  If there
> IS such a beastie, please let me know.

Well, here is a totally stupid implementation of an int to binary 
string function (probably require Python 2.2, but is easily 
backported).  Feel free to use, or improve on it.  It makes 
lexicographically ordered binary strings out of non-negative, non-float 
numbers.

-----------------------------------------------------------
def tobinarystr( num, maxbits=32 ):
    """Convert a POSITIVE, non-float number to a base-2 string."""

    l = []
    for i in range( maxbits ):
        l.append( str( int( num & 1 ) ) )
        num >>= 1
    l.reverse()
    return "".join( l )

def print_all_binary_strings( _range ):
    for num in _range:
        print tobinarystr( num )

def assert_ordering_on_binary_strings( max_num ):
    for i in range( max_num ):
        assert( tobinarystr( i ) < tobinarystr( i + 1 ) )

print_all_binary_strings( [0, 1, 2, 3, 32676, 2**31, 2**31 + 1] )
assert_ordering_on_binary_strings( 10000 )


-- 

Chad Netzer
cnetzer at mail.arc.nasa.gov





More information about the Python-list mailing list