# Bitwise operators

• (2 Pages)
• 1
• 2

## 17 Replies - 7619 Views - Last Post: 16 December 2010 - 11:57 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=205190&amp;s=bc6f5ad8fb9024656c0e598184b99846&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #16 Ronald91

Reputation: 11
• Posts: 31
• Joined: 26-April 09

## Re: Bitwise operators

Posted 14 December 2010 - 01:15 PM

I have no experience with python, but I use bit-wise operators extensively in C. I typical program the firmware for micro-controllers and one peripheral where I use bit-wise operators is the LCD screen. The LCD on the I-O board that I typically use has four data pins for inputs and four for outputs and LCD's display ASCII characters which is eight bits. So here is a function that uses bit-wise operators to configure the LCD to accept an ASCII character and display it correctly.

```void putcLCD(char cx)
{
char temp;
temp = cx;
LCD_DAT |= LCD_RS;    /* select LCD data register */
LCD_DAT |= LCD_E;     /* pull E signal to high */
cx &= 0xF0;           /* clear the lower 4 bits */
cx >>= 2;             /* shift to match the LCD data pins */
LCD_DAT = cx|LCD_E_RS;/* output upper 4 bits, E, and RS */
asm("nop");
asm("nop");
asm("nop");
LCD_DAT &= (~LCD_E);  /* pull E to low */
cx = temp & 0x0F;     /* get the lower 4 bits */
LCD_DAT |= LCD_E;     /* pull E to high */
cx <<= 2;             /* shift to match the LCD data pins */
LCD_DAT = cx|LCD_E_RS;/* output lower 4 bits, E, and RS */
asm("nop");
asm("nop");
asm("nop");
LCD_DAT &= (~LCD_E);  /* pull E to low */
delayby50us(1);
}

```

### #17 Motoma

Reputation: 452
• Posts: 797
• Joined: 08-June 10

## Re: Bitwise operators

Posted 15 December 2010 - 08:11 AM

I'm surprised no one has mentioned networking yet. Take for instance, a client and server negotiating connection options. The following example sends 4 flags in one byte, where your basic struct.pack would use 4 bytes. I believe just send()ing a bool results in 1 byte each as well.

Client side:
```version = 341

option1 = True
option2 = False
option3 = True
option4 = True

#...

sock.connect((server, port))
negotiation = struct.pack('!LB', version, option1 | option2<<1 | option3<<2 | option4<<3)
sock.send(negotiation)

```

Server side:
```#...

version, options = struct.unpack('!LB', client.recv(5))
option1 = bool(options & 1)
option2 = bool(options & 1<<1)
option3 = bool(options & 1<<2)
option4 = bool(options & 1<<3)

```

This post has been edited by Motoma: 15 December 2010 - 08:13 AM

### #18 atraub

• Pythoneer

Reputation: 803
• Posts: 2,141
• Joined: 23-December 08

## Re: Bitwise operators

Posted 16 December 2010 - 11:57 AM

These examples are really cool, albeit complex haha.