Home > Net >  Write to a range of perl array
Write to a range of perl array

Time:08-24

I have a 32-bit array, @data Want to write zeros for [16] to [31] Are there shorter methods to do this?

splice(@data,16,16,(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))

CodePudding user response:

You can use an array slice instead of splice to assign a list to a range of indices all at once:

@data[16..31] = (0) x 16;

CodePudding user response:

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

can be written as

( 0 ) x 16

So,

splice( @data, 16, 16, ( 0 ) x 16 );

That said, it's weird to use an array for bits. We'd normally use a number.

To keep only the least significant 16 bits, we'd use

$data &= 0xFFFF;

To keep only the most significant 16 bits of 32, we'd use

$data &= 0xFFFF0000;

or

$data &= ~0xFFFF;
  •  Tags:  
  • perl
  • Related