Right shift a binary no and get the shifted bits in a variableAppending 0 before binary number based on a value in a variableHow do I get values by Perl string operations?Why does my Perl script die with an “out of memory” exception?Perl pack/unpack/shiftHow can I do 64-bit hex/decimal arithmetic AND output a full number in HEX as string in Perl?problems comparing variables assigned within a foreach statementHow to convert hex to string of hexcutting a portion of url using regular expression in perlHow to perform operation on specific bits in perlGetting Error of Modification of a read-only value attemptedAppending 0 before binary number based on a value in a variable

What would be the safest way to drop thousands of small, hard objects from a typical, high wing, GA airplane?

Are there any Saints that have miraculously overcome death (should have died, but did not)?

Why aren't there any women super GMs?

Strategy to pay off revolving debt while building reserve savings fund?

Why are there few or no black super GMs?

Why does a tetrahedral molecule like methane have a dipole moment of zero?

When can a polynomial be written as a polynomial function of another polynomial?

How to find location on Cambridge-Mildenhall railway that still has tracks/rails?

Inscriptio Labyrinthica

Amira L'Akum not on Shabbat

Why were these characters absent in Spider-Man: Far From Home?

Mass Spell Recursion & Storm

Compiler only complains about the ambiguous overloaded functions when the parameter is 0

Zhora asks Deckard: "Are you for real?" Was this meant to be significant?

manipulate a list: replace random position of a specific integer n times by 0

How can electric field be defined as force per charge, if the charge makes its own, singular electric field?

Why did my "seldom" get corrected?

Can firbolgs cast their racial Detect Magic spell as a ritual?

The most secure way to handle someone forgetting to verify their account?

How do you give a date interval with diffuse dates?

Obtaining head and parts without evaluation

Why is Google approaching my VPS machine?

Does unblocking power bar outlets through short extension cords increase fire risk?

Can Error correction and detection be done with out adding extra bits?



Right shift a binary no and get the shifted bits in a variable


Appending 0 before binary number based on a value in a variableHow do I get values by Perl string operations?Why does my Perl script die with an “out of memory” exception?Perl pack/unpack/shiftHow can I do 64-bit hex/decimal arithmetic AND output a full number in HEX as string in Perl?problems comparing variables assigned within a foreach statementHow to convert hex to string of hexcutting a portion of url using regular expression in perlHow to perform operation on specific bits in perlGetting Error of Modification of a read-only value attemptedAppending 0 before binary number based on a value in a variable






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a binary no say and I have a value in variable say value = 4.
I want to right shift the binary no by no of bits stored in "value" variable and then want to store the shifted bits in a variable and also want to save binary no obtained after right shift in another variable



Example:



binary_number = 110000001
value =4
then shifting no of bits in "value" to right (11000001 >> value)


Now I want to finally have two variables one containing the binary no after shift and one variable with shifted bits.



For above example the solution that I want is



right_shifted_binary = 11000
bits_shifted = 0001


I can not find a proper documentation for the problem as most of the problem are telling about arithmetic right shift.










share|improve this question
























  • Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

    – Dada
    Mar 26 at 10:12












  • I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

    – Stefan Becker
    Mar 26 at 11:06











  • @StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

    – Dada
    Mar 26 at 12:34


















0















I have a binary no say and I have a value in variable say value = 4.
I want to right shift the binary no by no of bits stored in "value" variable and then want to store the shifted bits in a variable and also want to save binary no obtained after right shift in another variable



Example:



binary_number = 110000001
value =4
then shifting no of bits in "value" to right (11000001 >> value)


Now I want to finally have two variables one containing the binary no after shift and one variable with shifted bits.



For above example the solution that I want is



right_shifted_binary = 11000
bits_shifted = 0001


I can not find a proper documentation for the problem as most of the problem are telling about arithmetic right shift.










share|improve this question
























  • Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

    – Dada
    Mar 26 at 10:12












  • I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

    – Stefan Becker
    Mar 26 at 11:06











  • @StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

    – Dada
    Mar 26 at 12:34














0












0








0








I have a binary no say and I have a value in variable say value = 4.
I want to right shift the binary no by no of bits stored in "value" variable and then want to store the shifted bits in a variable and also want to save binary no obtained after right shift in another variable



Example:



binary_number = 110000001
value =4
then shifting no of bits in "value" to right (11000001 >> value)


Now I want to finally have two variables one containing the binary no after shift and one variable with shifted bits.



For above example the solution that I want is



right_shifted_binary = 11000
bits_shifted = 0001


I can not find a proper documentation for the problem as most of the problem are telling about arithmetic right shift.










share|improve this question
















I have a binary no say and I have a value in variable say value = 4.
I want to right shift the binary no by no of bits stored in "value" variable and then want to store the shifted bits in a variable and also want to save binary no obtained after right shift in another variable



Example:



binary_number = 110000001
value =4
then shifting no of bits in "value" to right (11000001 >> value)


Now I want to finally have two variables one containing the binary no after shift and one variable with shifted bits.



For above example the solution that I want is



right_shifted_binary = 11000
bits_shifted = 0001


I can not find a proper documentation for the problem as most of the problem are telling about arithmetic right shift.







perl






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 11:08









Stefan Becker

4,5813 gold badges11 silver badges25 bronze badges




4,5813 gold badges11 silver badges25 bronze badges










asked Mar 26 at 10:00









rikkirikki

1099 bronze badges




1099 bronze badges












  • Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

    – Dada
    Mar 26 at 10:12












  • I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

    – Stefan Becker
    Mar 26 at 11:06











  • @StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

    – Dada
    Mar 26 at 12:34


















  • Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

    – Dada
    Mar 26 at 10:12












  • I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

    – Stefan Becker
    Mar 26 at 11:06











  • @StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

    – Dada
    Mar 26 at 12:34

















Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

– Dada
Mar 26 at 10:12






Can you give a bit of context? This sounds like an XY problem. Typically, doing the shift on decimal numbers would make more sense. However, if you are sure that this is what you want to do, then use substr (what you call a "binary number" is seen by Perl as a string, not a number).

– Dada
Mar 26 at 10:12














I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

– Stefan Becker
Mar 26 at 11:06





I assume that $binary_number is an integer scalar and not a string? If it would be a string you could simply use substr() to extract the right bits.

– Stefan Becker
Mar 26 at 11:06













@StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

– Dada
Mar 26 at 12:34






@StefanBecker Given OP's previous question, I suppose that $binary_number is a string, but I might be wrong. (and that information should definitely be in the question: OP, please, clarify that)

– Dada
Mar 26 at 12:34













1 Answer
1






active

oldest

votes


















1














Generate a bit mask based on $value and use the AND (&) operator:



#!/usr/bin/perl
use warnings;
use strict;

my $binary = 0b110000001;
my $value = 4;

# create mask with $value left-most bits 1
my $mask = ~(~0 << $value);

print "INPUT: ", unpack("B*", pack("N", $binary)), " ($binary)n";

# right shift by $value bits
my $right_shifted_binary = $binary >> $value;
print "RIGHT: ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)n";

# extract "remainder" of shift using mask
my $bits_shifted = $binary & $mask;
print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)n";

exit 0;


Test run:



$ perl dummy.pl
INPUT: 00000000000000000000000110000001 (385)
RIGHT: 00000000000000000000000000011000 (24)
REMAINDER: 00000000000000000000000000000001 (1)

# Proof
$ echo "24 * 16 + 1" | bc
385



If the binary number is given as string you can convert it to an integer first:



my $binary_string = "110000001";
my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));


But if it is already a string then the solution would be much simpler:



#!/usr/bin/perl
use warnings;
use strict;

my $binary_string = "110000001";
my $value = 4;

print "INPUT: $binary_stringn";
print "RIGHT: ", substr($binary_string, 0, -$value), "n";
print "REMAINDER: ", substr($binary_string, -$value), "n";

exit 0:


$ perl dummy.pl
INPUT: 110000001
RIGHT: 11000
REMAINDER: 0001





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354295%2fright-shift-a-binary-no-and-get-the-shifted-bits-in-a-variable%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Generate a bit mask based on $value and use the AND (&) operator:



    #!/usr/bin/perl
    use warnings;
    use strict;

    my $binary = 0b110000001;
    my $value = 4;

    # create mask with $value left-most bits 1
    my $mask = ~(~0 << $value);

    print "INPUT: ", unpack("B*", pack("N", $binary)), " ($binary)n";

    # right shift by $value bits
    my $right_shifted_binary = $binary >> $value;
    print "RIGHT: ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)n";

    # extract "remainder" of shift using mask
    my $bits_shifted = $binary & $mask;
    print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)n";

    exit 0;


    Test run:



    $ perl dummy.pl
    INPUT: 00000000000000000000000110000001 (385)
    RIGHT: 00000000000000000000000000011000 (24)
    REMAINDER: 00000000000000000000000000000001 (1)

    # Proof
    $ echo "24 * 16 + 1" | bc
    385



    If the binary number is given as string you can convert it to an integer first:



    my $binary_string = "110000001";
    my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));


    But if it is already a string then the solution would be much simpler:



    #!/usr/bin/perl
    use warnings;
    use strict;

    my $binary_string = "110000001";
    my $value = 4;

    print "INPUT: $binary_stringn";
    print "RIGHT: ", substr($binary_string, 0, -$value), "n";
    print "REMAINDER: ", substr($binary_string, -$value), "n";

    exit 0:


    $ perl dummy.pl
    INPUT: 110000001
    RIGHT: 11000
    REMAINDER: 0001





    share|improve this answer





























      1














      Generate a bit mask based on $value and use the AND (&) operator:



      #!/usr/bin/perl
      use warnings;
      use strict;

      my $binary = 0b110000001;
      my $value = 4;

      # create mask with $value left-most bits 1
      my $mask = ~(~0 << $value);

      print "INPUT: ", unpack("B*", pack("N", $binary)), " ($binary)n";

      # right shift by $value bits
      my $right_shifted_binary = $binary >> $value;
      print "RIGHT: ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)n";

      # extract "remainder" of shift using mask
      my $bits_shifted = $binary & $mask;
      print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)n";

      exit 0;


      Test run:



      $ perl dummy.pl
      INPUT: 00000000000000000000000110000001 (385)
      RIGHT: 00000000000000000000000000011000 (24)
      REMAINDER: 00000000000000000000000000000001 (1)

      # Proof
      $ echo "24 * 16 + 1" | bc
      385



      If the binary number is given as string you can convert it to an integer first:



      my $binary_string = "110000001";
      my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));


      But if it is already a string then the solution would be much simpler:



      #!/usr/bin/perl
      use warnings;
      use strict;

      my $binary_string = "110000001";
      my $value = 4;

      print "INPUT: $binary_stringn";
      print "RIGHT: ", substr($binary_string, 0, -$value), "n";
      print "REMAINDER: ", substr($binary_string, -$value), "n";

      exit 0:


      $ perl dummy.pl
      INPUT: 110000001
      RIGHT: 11000
      REMAINDER: 0001





      share|improve this answer



























        1












        1








        1







        Generate a bit mask based on $value and use the AND (&) operator:



        #!/usr/bin/perl
        use warnings;
        use strict;

        my $binary = 0b110000001;
        my $value = 4;

        # create mask with $value left-most bits 1
        my $mask = ~(~0 << $value);

        print "INPUT: ", unpack("B*", pack("N", $binary)), " ($binary)n";

        # right shift by $value bits
        my $right_shifted_binary = $binary >> $value;
        print "RIGHT: ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)n";

        # extract "remainder" of shift using mask
        my $bits_shifted = $binary & $mask;
        print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)n";

        exit 0;


        Test run:



        $ perl dummy.pl
        INPUT: 00000000000000000000000110000001 (385)
        RIGHT: 00000000000000000000000000011000 (24)
        REMAINDER: 00000000000000000000000000000001 (1)

        # Proof
        $ echo "24 * 16 + 1" | bc
        385



        If the binary number is given as string you can convert it to an integer first:



        my $binary_string = "110000001";
        my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));


        But if it is already a string then the solution would be much simpler:



        #!/usr/bin/perl
        use warnings;
        use strict;

        my $binary_string = "110000001";
        my $value = 4;

        print "INPUT: $binary_stringn";
        print "RIGHT: ", substr($binary_string, 0, -$value), "n";
        print "REMAINDER: ", substr($binary_string, -$value), "n";

        exit 0:


        $ perl dummy.pl
        INPUT: 110000001
        RIGHT: 11000
        REMAINDER: 0001





        share|improve this answer















        Generate a bit mask based on $value and use the AND (&) operator:



        #!/usr/bin/perl
        use warnings;
        use strict;

        my $binary = 0b110000001;
        my $value = 4;

        # create mask with $value left-most bits 1
        my $mask = ~(~0 << $value);

        print "INPUT: ", unpack("B*", pack("N", $binary)), " ($binary)n";

        # right shift by $value bits
        my $right_shifted_binary = $binary >> $value;
        print "RIGHT: ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)n";

        # extract "remainder" of shift using mask
        my $bits_shifted = $binary & $mask;
        print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)n";

        exit 0;


        Test run:



        $ perl dummy.pl
        INPUT: 00000000000000000000000110000001 (385)
        RIGHT: 00000000000000000000000000011000 (24)
        REMAINDER: 00000000000000000000000000000001 (1)

        # Proof
        $ echo "24 * 16 + 1" | bc
        385



        If the binary number is given as string you can convert it to an integer first:



        my $binary_string = "110000001";
        my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));


        But if it is already a string then the solution would be much simpler:



        #!/usr/bin/perl
        use warnings;
        use strict;

        my $binary_string = "110000001";
        my $value = 4;

        print "INPUT: $binary_stringn";
        print "RIGHT: ", substr($binary_string, 0, -$value), "n";
        print "REMAINDER: ", substr($binary_string, -$value), "n";

        exit 0:


        $ perl dummy.pl
        INPUT: 110000001
        RIGHT: 11000
        REMAINDER: 0001






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 26 at 11:12

























        answered Mar 26 at 10:42









        Stefan BeckerStefan Becker

        4,5813 gold badges11 silver badges25 bronze badges




        4,5813 gold badges11 silver badges25 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354295%2fright-shift-a-binary-no-and-get-the-shifted-bits-in-a-variable%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현