[ I went sideways a bit since this is a learning exercise. Hopefully, this will put you in the right mindset to solve similar problems in the future. ]

My desired output to print 0b11110000 as 0xF0 but all I got was 0

This alone isn't very clear.

Is your input the string 0b11110000, the number 0b11110000 (240) or the character 0b11110000 (240)?

Is your desired output the string 0xF0, the number 0xF0 (240) or the character 0xF0 (240)?

One would generally convert the input to a number,

If your input is the string 0b11110000my $num = oct($input);
If your input is the number 240my $num = $input;
If your input is the character 240my $num = ord($input);
If your input is the character 240my $num = unpack('C', $input);

do something with it, then format the number as desired.

If your desired output is the string 0xF0my $output = sprintf("0x%02X", $num);
If your desired output is the number 240my $output = $num;
If your desired output is the character 240my $output = chr($num);
If your desired output is the character 240my $output = pack('C', $num);

Looking at your code, you want the the string 0xF0 from character 0b11110000, so

printf("0x%02X", ord($input));
or
printf("0x%02X", unpack('C', $input));

oct, ord, unpack, sprintf, printf, chr, pack


In reply to Re: Printing byte as 2 Hex characters by ikegami
in thread Printing byte as 2 Hex characters by ShiningPerl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.