"be consistent" PerlMonks

### Re: Displaying bit-vectors with Most Significant Bits to the left?

by johngg (Canon)
 on Jan 05, 2020 at 12:18 UTC Need Help??

Creating the vector in one 16-bit operation rather than several 1-bit operations simplifies the unpack process.

```johngg@shiraz:~/perl/Monks\$ perl -Mstrict -Mwarnings -E '
my @bitPosns = ( 0, 2, 8, 9, 10 );
my \$val;
\$val        += 2 ** \$_ for @bitPosns;
my \$vec;
vec( \$vec, 0, 16 ) = \$val;
say unpack q{B16}, \$vec;'
0000011100000101

Six of one, a half dozen of the other I suppose.

Cheers,

JohnGG

• Comment on Re: Displaying bit-vectors with Most Significant Bits to the left?

Replies are listed 'Best First'.
Re^2: Displaying bit-vectors with Most Significant Bits to the left?
by ikegami (Pope) on Jan 05, 2020 at 14:21 UTC

The OP didn't give any indication that \$m0 was different than expected. Changing the value of \$m0 doesn't seem appropriate. But if it is, there are two improvements you can make.

When doing bit arithmetic, most people prefer to use actual bit arithmetic instead of powers. Not only is it more intuitive to use operations that match one's mental model, your approach fails if a bit is already set. Replace

```\$val += 2 ** \$_

with

```\$val |= 1 << \$_

As evidenced by these posts, vec is quite weird, so it's surely best to avoid it if it doesn't offer a benefit.

```my \$vec;
vec( \$vec, 0, 16 ) = \$val;

can be replaced with

```my \$vec = pack 'n', \$val;

> vec is quite weird, so it's surely best to avoid it if it doesn't offer a benefit.

I think it's trying to hide the machine representation of a number.

I "grew up" on motorola, that's why I'm still confused.

But vec's approach might provide reproducible results on different architectures.

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

But vec's approach might provide reproducible results on different architectures.

Each of the snippets I posted produces the same output on both little-endian and big-endian machines.

With pack, you say what you want, and you get it. It's far cleaner than being told what you're going to get —sometimes LE, sometimes BE, based on the size of the third arg— and having to work around that.

Create A New User
Node Status?
node history
Node Type: note [id://11110972]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2020-05-25 07:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
If programming languages were movie genres, Perl would be:

Results (144 votes). Check out past polls.

Notices?