Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: How can I set a bit to 0 ?

by BillKSmith (Monsignor)
on May 28, 2022 at 22:46 UTC ( [id://11144258]=note: print w/replies, xml ) Need Help??


in reply to Re^2: How can I set a bit to 0 ?
in thread How can I set a bit to 0 ?

Lines 21 thru 23 of the following example demonstrate operations on individual bits, specified by their position, of a status word. The difficulty arises when we need to input or output this word. We need the bytes in the order that our hardware expects them ("endianness") and we want the position 0 to refer to the most significant bit.

I created a disc file which contains nothing but a 16-bit status word and verified the exact contents of that file with the utility "xxd" (came packaged with vim). My example reads that status word, makes a few changes, and writes it back out to another file. Again I use xxd to verify that I made the changes that I intended.

OK, I admit that lines 11 thru 19 and 25 thru 33 were developed empirically for this use of vec on my 64-bit intel machine. They are not portable to other environments but should work, without change, on any application on this or similar machine.

use strict; use warnings; my $stats; open my $DEVICE_IN, "<", 'stat.dat' or die "Cannot open input device: $!"; $stats = <$DEVICE_IN>; close $DEVICE_IN; $stats = pack( 'b16', reverse( unpack( 'B16', $stats ) ) ); vec($stats, 2, 1) = 0; # Reset bit 2 vec($stats, 6, 1) = 1; # Set bit 6 vec($stats, 10, 1) ^= 1; # Toggle bit 10 $stats = pack( 'b16', reverse( unpack( 'B16', $stats ) ) ); open my $DEVICE_OUT, ">", 'newstat.dat' or die "Cannot open output device: $!"; print $DEVICE_OUT $stats; close $DEVICE_OUT;

Here is the content of the two data files (displayed by xxd) after this example runs

C:\Users\Bill\forums\monks>xxd stat.dat 00000000: f531 .1 C:\Users\Bill\forums\monks>xxd newstat.dat 00000000: d711 .. C:\Users\Bill\forums\monks>

Note: There is no guarantee that traditional bit masking will eliminate this problem in I/O. It might, but testing is still required.

Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11144258]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2024-04-23 16:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found