Is there a module that sets the parity of a string? I have an
application that needs to communicate with a host using even parity
So what I need is before sending the message, convert it from space to
even parity. And when I get the response I need to convert that from
even to space parity.
The perl module String::Parity is what I have used to do this under perl.
Chris 8 5235
snacktime wrote: Is there a module that sets the parity of a string? I have an application that needs to communicate with a host using even parity So what I need is before sending the message, convert it from space to even parity. And when I get the response I need to convert that from even to space parity.
By what means are the messages being delivered? I've rarely
seen parity used outside of simple RS-232-style serial communications.
Certainly not (in my experience, though it's doubtless been done)
in TCP/IP based stuff. And if it's serial, parity can be
supplied at a lower level than your code.
As to the specific question: a module is not really required.
The parity value of a character depends only on the binary
value of that one byte, so a simple 128-byte substitution
table is all you need, plus a call to string.translat e for
each string.
-Peter
Peter Hansen wrote: snacktime wrote: Is there a module that sets the parity of a string?
As to the specific question: a module is not really required.
But here's one for you anyway. It raises an exception if any
input character is non-ASCII, otherwise when you call set_parity()
with a string and a parity parameter of 'even', 'mark', 'none',
'odd', or 'space', it returns a string of the same length with
the high (parity) bits set appropriately.
'''parity module for python'''
# Copyright 2005 Engenuity Corporation
# Released under the "MIT license"
# at http://www.opensource.org/licenses/mit-license.php
import string
import operator
def _makeTable(pari ty):
bitMap = {'even': [0,128], 'odd': [128,0], 'mark': [128,128]}
table = []
for c in range(128):
even_odd = (sum(bool(c & 1<<b) for b in range(8))) & 1
cp = chr(c | bitMap.get(pari ty, [0,0])[even_odd])
table.append(cp )
table.extend(ch r(c) for c in range(128, 256))
table = ''.join(table)
return table, table[128:]
_map = {}
for parity in 'even odd mark space none'.split():
_map[parity] = _makeTable(pari ty)
def set_parity(data , parity='none'):
'''return string with parity bits, accepting only ASCII characters
(0..127) as input'''
out = string.translat e(data, *_map[parity.lower()])
if len(out) != len(data):
raise ValueError('non-ASCII characters in input')
else:
return out
if __name__ == '__main__':
print 'Running self-tests for parity.py'
# check for invalid input handling
for input in [ '\xff', '\x80', 'test\xA0ing' ]:
try:
set_parity(inpu t)
except ValueError:
pass
else:
assert False, 'no exception for non-ASCII input'
# check for various valid inputs
for i, (parity, input, expected) in enumerate([
('space', 'test', 'test'),
('SPACE', '\x00\x7f', '\x00\x7f'),
('mark', 'test', '\xf4\xe5\xf3\x f4'),
('Odd', '\x00test\x7f', '\x80\xf4\xe5s\ xf4\x7f'),
('even', '\x00\x01\x02\x 03test\x7d\x7e\ x7f',
'\x00\x81\x82\x 03te\xf3t\x7d\x 7e\xff'),
]):
actual = set_parity(inpu t, parity)
assert expected == actual, 'case %d: %r != %r' % (i, expected, actual)
print 'All tests passed.'
Peter Hansen wrote: snacktime wrote: Is there a module that sets the parity of a string? I have an application that needs to communicate with a host using even parity
So what I need is before sending the message, convert it from space
to even parity. And when I get the response I need to convert that
from even to space parity. By what means are the messages being delivered? I've rarely seen parity used outside of simple RS-232-style serial
communications. Certainly not (in my experience, though it's doubtless been done) in TCP/IP based stuff. And if it's serial, parity can be supplied at a lower level than your code.
As to the specific question: a module is not really required. The parity value of a character depends only on the binary value of that one byte, so a simple 128-byte substitution table is all you need, plus a call to string.translat e for each string.
-Peter
And for converting back from even parity to space parity, either a
256-byte translation table, or a bit of bit bashing, like chr(ord(c) &
127), on each byte.
The bank story sounds eminently plausible to me. Pick up old system
where branch manager had to dial HO every evening, insert phone into
acoustic coupler, etc etc and dump it on the internet ...
On Sun, 23 Jan 2005 21:00:25 -0500, Peter Hansen <pe***@engcorp. com> wrote: Peter Hansen wrote: snacktime wrote: Is there a module that sets the parity of a string?
As to the specific question: a module is not really required.
But here's one for you anyway. It raises an exception if any input character is non-ASCII, otherwise when you call set_parity() with a string and a parity parameter of 'even', 'mark', 'none', 'odd', or 'space', it returns a string of the same length with the high (parity) bits set appropriately.
Thanks for the code example, I'm not quite up to speed on python
enough to make this a trivial exercise as of yet.
Chris
I'm trying to figure out why the following code transforms ascii STX
(control-b) into "\x82". The perl module I use returns a value of
"^B", and that is also what the application I am communicating with
expects to see. Some ascii characters such as FS and GS come through
fine, but STX and ETX get transformed incorrectly (at least for what I
need they do).
What am I missing here?
Chris But here's one for you anyway. It raises an exception if any input character is non-ASCII, otherwise when you call set_parity() with a string and a parity parameter of 'even', 'mark', 'none', 'odd', or 'space', it returns a string of the same length with the high (parity) bits set appropriately.
'''parity module for python''' # Copyright 2005 Engenuity Corporation # Released under the "MIT license" # at http://www.opensource.org/licenses/mit-license.php
import string import operator
def _makeTable(pari ty): bitMap = {'even': [0,128], 'odd': [128,0], 'mark': [128,128]} table = [] for c in range(128): even_odd = (sum(bool(c & 1<<b) for b in range(8))) & 1 cp = chr(c | bitMap.get(pari ty, [0,0])[even_odd]) table.append(cp ) table.extend(ch r(c) for c in range(128, 256)) table = ''.join(table) return table, table[128:]
_map = {} for parity in 'even odd mark space none'.split(): _map[parity] = _makeTable(pari ty)
def set_parity(data , parity='none'): '''return string with parity bits, accepting only ASCII characters (0..127) as input''' out = string.translat e(data, *_map[parity.lower()]) if len(out) != len(data): raise ValueError('non-ASCII characters in input') else: return out
if __name__ == '__main__': print 'Running self-tests for parity.py'
# check for invalid input handling for input in [ '\xff', '\x80', 'test\xA0ing' ]: try: set_parity(inpu t) except ValueError: pass else: assert False, 'no exception for non-ASCII input'
# check for various valid inputs for i, (parity, input, expected) in enumerate([ ('space', 'test', 'test'), ('SPACE', '\x00\x7f', '\x00\x7f'), ('mark', 'test', '\xf4\xe5\xf3\x f4'), ('Odd', '\x00test\x7f', '\x80\xf4\xe5s\ xf4\x7f'), ('even', '\x00\x01\x02\x 03test\x7d\x7e\ x7f', '\x00\x81\x82\x 03te\xf3t\x7d\x 7e\xff'), ]): actual = set_parity(inpu t, parity) assert expected == actual, 'case %d: %r != %r' % (i, expected, actual)
print 'All tests passed.' -- http://mail.python.org/mailman/listinfo/python-list
Correction on this, ETX is ok, it seems to be just STX with the data I am using.
Chris
On Wed, 26 Jan 2005 11:50:46 -0800, snacktime <sn*******@gmai l.com> wrote: I'm trying to figure out why the following code transforms ascii STX (control-b) into "\x82". The perl module I use returns a value of "^B", and that is also what the application I am communicating with expects to see. Some ascii characters such as FS and GS come through fine, but STX and ETX get transformed incorrectly (at least for what I need they do).
snacktime wrote: Correction on this, ETX is ok, it seems to be just STX with the data I am using.
On Wed, 26 Jan 2005 11:50:46 -0800, snacktime <sn*******@gmai l.com> wrote:
I'm trying to figure out why the following code transforms ascii STX (control-b) into "\x82". The perl module I use returns a value of "^B", and that is also what the application I am communicating with expects to see. Some ascii characters such as FS and GS come through fine, but STX and ETX get transformed incorrectly (at least for what I need they do).
I didn't see the first post, which you quoted above... more newsfeed
or python-list misalignment I guess. :-(
Anyway, since STX '\x02' has only one bit set, if you are setting
the parity bit for "even" parity, then naturally it will be set
(in order to make the total number of "on" bits an even number),
so you get '\x82' (which has two bits set). ETX, on the other
hand '\x03' already has two bits set, so the high bit is left alone.
It sounds as though you need to examine the specification
for the receiving system in more detail, or perhaps seek
clarification from the other party involved in this system
you're working with. If you have examples that show STX and
ETX both being transmitted, around other data which itself
has had the parity bit set for even parity, then clearly (a)
the folks involved in designing that system are idiots
<0.5 wink> and (b) you'll have to modify the way you are
forming the transmission packet. It appears they may want
the STX/ETX pair to be sent without being affected by the
parity process...
-Peter
Argh, never mind my mistake. I wasn't logging the data correctly the
parity conversion works fine.
Chris This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Petr Jakes |
last post by:
Hi,
I am trying to set-up communication to the coin change-giver from my
Linux box using the Python code. The change giver uses MDB (Multi Drop
Bus) serial protocol to communicate with the master. MDB protocol is
the 9bit serial protocol:
(TX, RX lines only) 9600bps, 9bits, No Parity, 1 Start, 1 Stop.
I would like to control the UART "parity bit" to try to simulate 9bit
communication.
|
by: Peter Oliphant |
last post by:
OK, I'm mixing old style with new style, so sue me... : )
Will under old syntax, I'm able to create a SerialPort instance. But, when I
try to convert the Parity proerty to a String*, I get the following compiler
error:
error C3610: value type must be 'boxed'
Here is the code:
|
by: rsine |
last post by:
I have developed a program that sends a command through the serial port
to our business system and then reads from the buffer looking for a
number. Everything worked great on my WinXP system, but when I tried
the program on the Win98 system it will be running on, I get the
following error:
Cast from string "2076719" to type 'Long' is not valid
I am not sure why I only get this error on the Win98 system or how to go
about correcting...
|
by: Loren |
last post by:
I am using parity error checking as I receive data into
the input buffer from the comm port. The data I receive
consists of a parity error, followed by received data,
followed by a parity error. I can detect the first
parity error, and then the following data is processed
without a parity error, just like it should be, but then
the last byte of data, which should have a parity error,
doesn't detect the parity error. Am I just running...
|
by: nick.stefanov |
last post by:
I am trying to compute an even parity bit for a variable of type
char. Are there any C++, C# examples on how to first compute the bit
and then check it. Thank you very much ahead of time.
Nick
| |
by: Tonio Cartonio |
last post by:
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
Francesco
--
-------------------------------------
http://www.riscossione.info/
|
by: Radu Crisan |
last post by:
Hi all,
i have this RS232 settings
public static string portName;
public static Int16 baudRate = 19200;
public static Parity parity = Parity.Mark;
public static Int16 dataBits = 8;
public static StopBits stopBits = StopBits.One;
public static Handshake handShake = Handshake.None;
|
by: Toe001 |
last post by:
Can you please help me understand why I do not see the answer expected (Parity: Odd). Can I have an array of strings as constants? How do I index each string in the array?
const Parity = {'None', 'Odd', 'Even'};
char string;
sprintf(string, "Parity: %s", Parity);
printf(string);
Thanks
|
by: philbo30 |
last post by:
I admit, I didn't spend any time researching this yet so this is the
first step...
Is there a C function available to determine byte parity or is the
usual course to just count the 1s?
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |