Memory layout of a data structure: Difference between revisions

m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(10 intermediate revisions by 8 users not shown)
Line 35:
24 - XTC External clock
25 -
=={{header|6502 Assembly}}==
<syntaxhighlight lang="6502asm">soft_rs232_lo equ $20 ;%87654321
soft_rs232_hi equ $21 ;%-------9</syntaxhighlight>
 
The values $20 and $21 do not matter; any zero page memory location is acceptable. The comments explain which bit position represents which pin, written in the format one would write a binary literal in the assembler. A "-" means that particular bit is unused.
 
This example non-destructively writes a "1" to pin 3:
<syntaxhighlight lang="6502asm">LDA soft_rs232_lo
ora #%00000100
sta soft_rs232_lo</syntaxhighlight>
 
The common practice is to have "soft" ports in zero page which get written to the memory-mapped location of the actual hardware interface by only a single subroutine that is run at a fixed interval. All other routines only ever update the "soft" port. (Hardware ports such as this example are typically write-only so the only way to non-destructively write to individual bits is through this indirect method.)
=={{header|68000 Assembly}}==
Thanks to the low-level nature of assembly, this task is actually rather straightforward. Using <code>equ</code> directives we can easily abstract the bit numbers with convenient labels without having to remember what they are.
 
<syntaxhighlight lang="68000devpac">BIT_0 equ $1
BIT_1 equ $2
BIT_2 equ $4
BIT_3 equ $8
BIT_4 equ $10
BIT_5 equ $20
BIT_6 equ $40
BIT_7 equ $80
 
BIT_8 equ $100
BIT_9 equ $200
 
RS232_9_TD equ BIT_3
RS232_9_RD equ BIT_2
RS232_9_RTS equ BIT_7
RS232_9_CTS equ BIT_8
RS232_9_DSR equ BIT_6
RS232_9_SG equ BIT_5
RS232_9_CD equ BIT_1</syntaxhighlight>
 
With these aliases defined, we can easily write these constants, or any combination thereof, to the memory-mapped RS232 port.
 
(Disclaimer: I have no idea how this protocol actually works. So there's a good chance that these values should '''not''' be combined this way when working with actual RS232 hardware. But that's not really important to this task. I'm just showing how you can define constants and write them to the port.)
 
<syntaxhighlight lang="68000devpac">rs232_9pin_port equ $A00000
;I chose $A00000 arbitrarily as an example, its actual address depends on the wiring.
 
MOVE.W #RS232_9_CTS,rs232_9pin_port
MOVE.W #RS232_9_CTS|RS232_9_RD|RS232_9_SG,rs232_9pin_port ;bitwise OR can be used at compile time to combine the labels.</syntaxhighlight>
 
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">type Bit is mod 2;
type Rs_232_Layout is record
Carrier_Detect : Bit;
Line 60 ⟶ 105:
Clear_To_Send at 0 range 7..7;
Ring_Indicator at 0 range 8..8;
end record;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 67 ⟶ 112:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">MODE RSTWOTHREETWO = BITS;
INT ofs = bits width - 9;
INT
Line 86 ⟶ 131:
 
rs232 bits := bits pack((FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE));
print(("received data: ",received data ELEM rs232bits, new line))</langsyntaxhighlight>
Output:
<pre>
Line 95 ⟶ 140:
=={{header|C}}/{{header|C++}}==
Note: The order of the fields is implementation-defined (i.e. the first bit might be the least-significant one or the most-significant one). On GCC and MSVC++, the first bit is the least-significant one.
<langsyntaxhighlight lang="c">struct RS232_data
{
unsigned carrier_detect : 1;
Line 106 ⟶ 151:
unsigned clear_to_send : 1;
unsigned ring_indicator : 1;
};</langsyntaxhighlight>
The ":1" gives the number of allocated bits. For unused bits (e.g. pin 11 in the 25-pin version above) the field name can be omitted.
 
Line 115 ⟶ 160:
Implementation uses tango's BitArray structure.
{{libheader|tango}}
<langsyntaxhighlight Dlang="d">module controlFieldsInStruct;
 
import tango.core.BitArray;
Line 185 ⟶ 230:
 
return 0;
}</langsyntaxhighlight>
 
Output:
Line 193 ⟶ 238:
===Phobos version===
Not tested.
<langsyntaxhighlight lang="d">import std.bitmanip;
 
struct RS232_data {
Line 223 ⟶ 268:
}
 
void main() {}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
The following code examines the memory associated with Delphi "Sets." In the case, the program creates a set associated with the RS232 pin patterns. It then displays the content of memory showing how each item in the set is associated with a single bit in memory.
<syntaxhighlight lang="Delphi">
 
{Enumerate pin assignments}
 
type TRS232Pins = (rpCarrierDetect, rpReceivedData, rpTransmittedData,
rpDataTerminalReady, rpSignalGround, rpDataSetReady,
rpRequestToSend, rpClearToSend, rpRingIndicator);
{Make into a set}
type TPinSet = set of TRS232Pins;
 
var Pins: TPinSet; {Global variable holding a set of pins}
 
procedure ShowMemory(Memo: TMemo; Name: string; SetPins: TPinSet);
{Extract the set data from memory and display it}
var S: string;
var P: PWord;
begin
P:=@Pins;
Pins:=SetPins;
S:=Name;
S:=S+IntToBin(P^, 16, True);
Memo.Lines.Add(S);
end;
 
 
 
procedure ShowPinsMemory(Memo: TMemo);
begin
ShowMemory(Memo,'Empty: ',[]);
ShowMemory(Memo,'Carrier Detect: ',[rpCarrierDetect]);
ShowMemory(Memo,'Received Data: ',[rpReceivedData]);
ShowMemory(Memo,'Transmitted Data: ',[rpTransmittedData]);
ShowMemory(Memo,'Data Terminal Ready:',[rpDataTerminalReady]);
ShowMemory(Memo,'Signal Ground: ',[rpSignalGround]);
ShowMemory(Memo,'Data Set Ready: ',[rpDataSetReady]);
ShowMemory(Memo,'Request To Send: ',[rpRequestToSend]);
ShowMemory(Memo,'Clear To Send: ',[rpClearToSend]);
ShowMemory(Memo,'Ring Indicator: ',[rpRingIndicator]);
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Empty: 0000000000000000
Carrier Detect: 0000000000000001
Received Data: 0000000000000010
Transmitted Data: 0000000000000100
Data Terminal Ready:0000000000001000
Signal Ground: 0000000000010000
Data Set Ready: 0000000000100000
Request To Send: 0000000001000000
Clear To Send: 0000000010000000
Ring Indicator: 0000000100000000
</pre>
 
 
=={{header|Forth}}==
Low level hardware control is a typical use of Forth. None of this is standard, however, since hardware I/O mechanisms differ on different systems. Forth does not have a structure mechanism, much less bitfields. These would be represented instead via bitmask constants if doing real serial port control.
 
<langsyntaxhighlight lang="forth"> : masks ( n -- ) 0 do 1 i lshift constant loop ;
9 masks DCD RxD TxD DTR SG DSR RTS CTS RI</langsyntaxhighlight>
 
Example usage, assuming I/O primitives '''in''' and '''out''':
 
<langsyntaxhighlight lang="forth"> hex
3fd constant com1-ctrl
decimal
Line 257 ⟶ 363:
wait-rx
2/
loop drop ;</langsyntaxhighlight>
Of course, this is a very simplified view of the full RS-232 protocol. Also, although this represents the order of the pins in a D-9 connector, this would not necessarily be the same as the order of the bits in a control register.
Line 263 ⟶ 369:
=={{header|Fortran}}==
===Modern===
F90 introduced the ability to define compound data aggregates, as had been used from the start by COBOL in the 1960s. Thus, one could define <langsyntaxhighlight Fortranlang="fortran"> TYPE RS232PIN9
LOGICAL CARRIER_DETECT !1
LOGICAL RECEIVED_DATA !2
Line 273 ⟶ 379:
LOGICAL CLEAR_TO_SEND !8
LOGICAL RING_INDICATOR !9
END TYPE RS232PIN9 </langsyntaxhighlight>
But it would be nearly pointless to do so.
 
Line 297 ⟶ 403:
=={{header|Free Pascal}}==
The FPC (Free Pascal compiler) carefully defines the internal memory structure of data type in its “Programmer’s guide”.
<langsyntaxhighlight lang="pascal">program rs232(input, output, stdErr);
type
{$packEnum 2}{$scopedEnums off}
Line 319 ⟶ 425:
writeLn(binStr(signalMemoryStructure, bitSizeOf(signal)));
end;
end.</langsyntaxhighlight>
{{Out}}
<pre>0000000000010000</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' using bit fields
Line 340 ⟶ 446:
 
Print SizeOf(RS232_Pin9) '' 2 bytes
Sleep</langsyntaxhighlight>
 
=={{header|Go}}==
Go does not have named bits as part of the type system. Instead, constants are typically defined as shown. For a word of bits with special meanings like this, a type would be defined though, as shown. Static typing rules then control assignments and comparisons at the word level. At the bit level, it helps to follow naming conventions so that, say, using a 9-pin constant on a 25-pin word would be an obvious error in the source code.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 366 ⟶ 472:
p := RI9 | TD9 | CD9
fmt.Printf("Type=%T value=%#04x\n", p, p)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 374 ⟶ 480:
=={{header|J}}==
J does not support "structures", nor "fields in a structure". Instead, J supports arrays. And, of course, J could have labels corresponding to the elements of an array representing the state (voltage, current, logical bit value, whatever) of each pin of a 9-pin RS-232 plug:
<syntaxhighlight lang="j">default=: 0#~#|:'labels comments'=:|:(4 ({.@;:@{. ; }.)]);._2 {{)n
<lang j>labels=: <;._2]0 :0
CD Carrier detect
RD Received data
TD Transmitted data
Line 384 ⟶ 489:
CTS Clear to send
RI Ring indicator
}}
)</lang>
 
indices=: labels (i. ;: ::]) ]
ndx=: [ {~ [ indices ]
asgn=: {{ y (x indices m)} x }}</syntaxhighlight>
 
Example use:
 
<syntaxhighlight lang="j"> example=: default NB. new instance
example ndx 'RI CTS'
0 0
example=: example 'RI RTS TD' asgn 1 2 3
example ndx 'RI CTS'
1 0</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
public final class MemoryLayoutOfDataStructure {
 
public static void main(String[] aArgs) {
RS232Pins9 plug = new RS232Pins9();
System.out.println(plug.getPin("receivedData"));
plug.setPin(2, Status.ON);
System.out.println(plug.getPin("receivedData"));
plug.setPin("signalGround", Status.ON);
plug.displayPinStatus();
}
}
 
enum Status { OFF, ON }
final class RS232Pins9 {
public Status getPin(int aPinNumber) {
for ( Pin pin : Pin.values() ) {
if ( pin.pinNumber == aPinNumber ) {
return pin.status;
}
}
throw new IllegalArgumentException("Unknown pin number: " + aPinNumber);
}
public Status getPin(String aName) {
for ( Pin pin : Pin.values() ) {
if ( pin.name() == aName ) {
return pin.status;
}
}
throw new IllegalArgumentException("Unknown pin name: " + aName);
}
public void setPin(int aPinNumber, Status aStatus) {
for ( Pin pin : Pin.values() ) {
if ( pin.pinNumber == aPinNumber ) {
pin.status = aStatus;
}
}
}
public void setPin(String aName, Status aStatus) {
for ( Pin pin : Pin.values() ) {
if ( pin.name() == aName ) {
pin.status = aStatus;
}
}
}
public void displayPinStatus() {
for ( Pin pin : Pin.values() ) {
System.out.println(String.format("%-29s%s", pin.name() + " has status ", pin.status));
}
}
private enum Pin {
carrierDetect(1, Status.OFF), receivedData(2, Status.OFF), transmittedData(3, Status.OFF),
dataTerminalReady(4, Status.OFF), signalGround(5, Status.OFF), dataSetReady(6, Status.OFF),
requestToSend(7, Status.OFF), clearToSend(8, Status.OFF), ringIndicator(9, Status.OFF);
private Pin(int aPinNumber, Status aStatus) {
pinNumber = aPinNumber;
status = aStatus;
}
private int pinNumber;
private Status status;
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
OFF
ON
carrierDetect has status OFF
receivedData has status ON
transmittedData has status OFF
dataTerminalReady has status OFF
signalGround has status ON
dataSetReady has status OFF
requestToSend has status OFF
clearToSend has status OFF
ringIndicator has status OFF
</pre>
 
=={{header|Julia}}==
Line 402 ⟶ 612:
</pre>
We can then make the following code for a new serial port type:
<syntaxhighlight lang="julia">
<lang Julia>
mutable struct NinePinSerialPort
pins::BitArray
Line 426 ⟶ 636:
println("CTS pin of port, which is pin $CTS, is now $(port[CTS])")
println("port is now: $port")
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 439 ⟶ 649:
 
However, if access by both position and name is required, then a data class with 9 named boolean properties would be more suitable. This automatically generates functions called component1, component2 etc. to get the pin values by pin number. However, a function needs to be written manually to set pin values by pin number:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
const val OFF = false
Line 480 ⟶ 690:
println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name
println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name
}</langsyntaxhighlight>
 
{{out}}
Line 493 ⟶ 703:
Defining structs in MATLAB is kind of bulky, making a class definition might be cleaner for this purpose. If you need to enumerate each pin rather than set the state of the pin using the name of the pin, you can use struct2cell() on the rs232 struct, which will return a cell array whose entries are the value of each of the structs fields in the order in which they were defined.
 
<langsyntaxhighlight MATLABlang="matlab">>> rs232 = struct('carrier_detect', logical(1),...
'received_data' , logical(1), ...
'transmitted_data', logical(1),...
Line 527 ⟶ 737:
[1]
[1]
[1]</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 537 ⟶ 747:
 
=== rs232.m ===
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module rs232.
 
Line 608 ⟶ 818:
 
:- end_module rs232.
</syntaxhighlight>
</lang>
 
=== rs232_main.m ===
<langsyntaxhighlight Mercurylang="mercury">:- module rs232_main.
 
:- interface.
Line 648 ⟶ 858:
 
:- end_module rs232_main.
</syntaxhighlight>
</lang>
 
==== Usage and output ====
Line 659 ⟶ 869:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
rs232Data = enum
carrierDetect,
Line 677 ⟶ 887:
let readValue: uint16 = 123
bv = cast[set[rs232Data]](readValue) # Conversion of a read value to bitvector
echo bv</langsyntaxhighlight>
Output:
<pre>273
Line 684 ⟶ 894:
=={{header|OCaml}}==
'''Library:''' [http://code.google.com/p/ocaml-extlib/ extlib]
<langsyntaxhighlight lang="ocaml">open ExtLib
class rs232_data = object
val d = BitSet.create 9
Line 708 ⟶ 918:
method set_ring_indicator b = (if b then BitSet.set else BitSet.unset) d 8
end
;;</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 716 ⟶ 926:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Bit::Vector::Minimal qw();
my $vec = Bit::Vector::Minimal->new(size => 24);
 
Line 745 ⟶ 955:
 
$vec->set($rs232{'RD Received data'}, 1);
$vec->get($rs232{'TC Transmit clock'});</langsyntaxhighlight>
 
=={{header|Phix}}==
Phix does not support bit-fields directly. The nearest/sanest thing to do probably goes something like this (completely untested)
 
<lang Phix>constant CD=1, RD=2, TD=3, DTR=4, ...
<!--<syntaxhighlight lang="phix">-->
atom addr = allocate(2) -- or wherever
<span style="color: #008080;">constant</span> <span style="color: #000000;">CD</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">RD</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">TD</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">DTR</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">...</span>
--read
<span style="color: #004080;">atom</span> <span style="color: #000000;">addr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">allocate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- or wherever
sequence bits = int_to_bits(peek2u(addr),16)
--read</span>
integer dtr = bits[DTR]
<span style="color: #004080;">sequence</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">int_to_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peek2u</span><span style="color: #0000FF;">(</span><span style="color: #000000;">addr</span><span style="color: #0000FF;">),</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
--write
<span style="color: #004080;">integer</span> <span style="color: #000000;">dtr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">DTR</span><span style="color: #0000FF;">]</span>
bits[DTR] = 1
<span style="color: #000080;font-style:italic;">--write</span>
poke2(addr,bits_to_int(bits))</lang>
<span style="color: #000000;">bits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">DTR</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #7060A8;">poke2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">addr</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">bits_to_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
 
Naturally, you would be well advised to sequester such grubby details away in a small and separate unit/source code file (eg RS232.e) with a domain specific public API that does not leak implementation details (eg keep those constants private). There are 1/2/4/8 byte variants of peek and poke, and int-to-bits can extract anything from 1 to 53 bits on a 32-bit runtime, or up to 64 on a 64-bit runtime.
Alternatively you could use bit-masks, or it may be possible to enhance builtins/cffi.e to manage bit-fields, then again the above C entry does not exactly inspire confidence.
Line 766 ⟶ 980:
'[http://software-lab.de/doc/refX.html#x| x|]',
or tested with '[http://software-lab.de/doc/refB.html#bit? bit?]'.
<langsyntaxhighlight PicoLisplang="picolisp"># Define bit constants
(for (N . Mask) '(CD RD TD DTR SG DSR RTS CTS RI)
(def Mask (>> (- 1 N) 1)) )
Line 772 ⟶ 986:
# Test if Clear to send
(when (bit? CTS Data)
... )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare 1 RS232_layout,
2 Carrier_Detect Bit(1),
Line 786 ⟶ 1,000:
2 Clear_To_Send Bit(1),
2 Ring_Indicator Bit(1);
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
The ctypes module allows for the creation of Structures that can map between the structures of C and python datatypes. Within Structures, [http://docs.python.org/library/ctypes.html#bit-fields-in-structures-and-unions bit fields] can be created.
 
<langsyntaxhighlight lang="python">from ctypes import Structure, c_int
 
rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
Line 803 ⟶ 1,017:
class RS232_25pin(Structure):
_fields_ = [(__, c_int, 1) for __ in rs232_25pin]</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 822 ⟶ 1,036:
((ctype-scheme->c _rs232) '(SG TD RI)) ; -> 276
((ctype-c->scheme _rs232) 276) ; -> '(TD SG RI)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
The following is specced to work, but implementation of shaped arrays is not quite complete.
<syntaxhighlight lang="raku" perl6line>enum T_RS232 <
carrier_detect
received_data
Line 841 ⟶ 1,055:
my bit @signal[T_RS232];
 
@signal[signal_ground] = 1;</langsyntaxhighlight>
In the absence of shaped arrays, you can do the usual bit-twiddling tricks on a native integer of sufficient size. (Such an integer could presumably be mapped directly to a device register.)
<syntaxhighlight lang="raku" perl6line>$signal +|= 1 +< signal_ground;</langsyntaxhighlight>
Using a native int is likelier to work on a big-endian machine in any case. Another almost-there solution is the mapping of C representational types into Raku for native interfaces, but it does not yet support bit fields.
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Decode Memory structure of RS-232 Plug Definition
* Not sure if I understood it completely :-) Open for corrections
Line 967 ⟶ 1,181:
res=res||bs
End
Return res</langsyntaxhighlight>
Output EBCDIC:
<pre>
Line 1,010 ⟶ 1,224:
===version 2===
Checks could be added to verify the number of pins selected, and also verify if the data (pin readings) specified is valid.
<langsyntaxhighlight lang="rexx">/*REXX program displays which pins are active of a 9 or 24 pin RS-232 plug. */
call rs_232 24, 127 /*the value for an RS-232 24 pin plug.*/
call rs_232 24, '020304x' /* " " " " " " " " */
Line 1,053 ⟶ 1,267:
say right(j, 5) 'pin is "on": ' @.pins.j
end /*j*/
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default (internal) inputs:
<pre>
Line 1,081 ⟶ 1,295:
=={{header|Ruby}}==
Uses the [http://redshift.sourceforge.net/bit-struct/ BitStruct] module, which is handy but awkward to instantiate objects.
<langsyntaxhighlight lang="ruby">require 'bit-struct'
 
class RS232_9 < BitStruct
Line 1,110 ⟶ 1,324:
puts sample2.inspect_detailed
 
puts "CD is #{sample2.cd == 1 ? 'on' : 'off'}"</langsyntaxhighlight>
 
<pre>num = 37
Line 1,136 ⟶ 1,350:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object Rs232Pins9 extends App {
 
val (off: Boolean, on: Boolean) = (false, true)
Line 1,175 ⟶ 1,389:
println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name
println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
This Tcl implementation represents the fields as bits in an integer. It provides two functions to get from symbolic pin names to the integer, and vice versa.
<langsyntaxhighlight lang="tcl">set rs232_bits {CD RD TD DTR SG DSR RTS CTS RI}
 
proc rs232_encode args {
Line 1,207 ⟶ 1,421:
catch $test res
if {$res ne $expected} {puts "$test -> $res, expected $expected"}
}</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 1,216 ⟶ 1,430:
It is not possible to vary this memory layout though, if lack of memory is a problem, one may be able to use bit arithmetic to pack more values into a Num.
 
As far as this task is concerned, below is a possible implementation for a 9-pin RRS-232 plug which allows access by pin name or number and provides a comprehensive print out of the current pin state.
<langsyntaxhighlight ecmascriptlang="wren">import "./seq" for Lst
import "./fmt" for Fmt
 
var ON = true
Line 1,262 ⟶ 1,476:
plug[3] = ON // set pin 3 by number
plug["DSR"] = "ON" // set pin 6 by name and using a string
System.print(plug) // print the state of the pins</langsyntaxhighlight>
 
{{out}}
Line 1,276 ⟶ 1,490:
9 RI = OFF
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">
Assuming RS-232 pin 1 is connected to bit 0 of an I/O port et cetera, the
bits can be assigned names, such as these:
 
def CD=1<<0, RD=1<<1, TD=1<<2, DTR=1<<3, DSR=1<<4, RTS=1<<5, CTS=1<<6, RI=1<<7;
def RS232=$10;
 
The 'port' command can then be used to access these pin signals by name like this:
port(RS232):= TD ! RTS;
if port(RS232) & RD then ...
 
Note: The 'port' command is implemented in the Intel x86 versions but not
in the Raspberry Pi or Windows (EXPL32) versions.
]</syntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|6502 Assembly}}
 
<syntaxhighlight lang="z80">softRS232_LO equ &C000 ;%87654321 (each bit represents the state of a numbered pin)
softRS232_HI equ &C001 ;%-------9
 
ld hl,softRS232_LO ;memory location of soft RS232 port
ld c,&00 ;&00 = the port that the RS232 is connected to.
;This is just an example, the actual port number depends on where the hardware is connected.
 
outi ;send the value contained in softRS232_LO thru port &00
outi ;send the value contained in softRS232_HI thru port &00</syntaxhighlight>
 
 
 
{{omit from|ACL2}}
9,476

edits