[Tutor] working with c_byte?

Alex Hall mehgcap at gmail.com
Sat Mar 24 04:51:24 CET 2012


Hi all,
I am trying to read battery information. I found an example that sets
up a ctypes structure to get the information from a kernel call, and
it works... except that I just realized the values of some fields are
added. For instance, a value of 1 means that the battery is "high",
and 8 means it is charging. I didn't realize until just now that
Windows will give both of these to me as 9, so the dict I set up to
see what the value is won't work. Similarly, a value of 255 is always
seen in Python as -128, even if I multiply it by -1 to flip it. The
value I'm working with is a ctypes.c_byte. Here is the data structure:
class SYSTEM_POWER_STATUS(ctypes.Structure):
 _fields_=[
  ("ACLineStatus", ctypes.c_byte),
  ("BatteryFlag", ctypes.c_byte),
  ("BatteryLifePercent", ctypes.c_byte),
  ("Reserved1", ctypes.c_byte),
  ("BatteryLifeTime", ctypes.wintypes.DWORD),
  ("BatteryFullLiveTime", ctypes.wintypes.DWORD)
 ]

and here is my dict to use when looking up the meaning of the BatteryFlag:
status_constants = {
 1:"high",
 2:"low",
 4:"critical",
 8:"charging",
 128:"no system battery",
 -128:"no system battery", #hack to get around odd negation of 128
flag... how to fix?
 255:"unknown"
}

Of course, 9 means the battery is high and charging, but how do I
interpret an arbitrary integer as the sum of its flags? Is there a
binary trick I can use? I could record all the 1s in the binary number
and look up their positions... but is there a simpler way? If I do
that, where is the sign bit in c_byte? TIA.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list