3

I have written a Perl script that takes an input hexadecimal value and then returns the binary equivalent. I need to sign that 8-bit integer and view the signed integer's value. This particular scenario does not seem to be covered in the Perl documentation that I have seen. The script is pasted below:

    #! perl
    use warnings;
    print "Enter hexidecimal number:";
    chomp ($hexNum = <STDIN>);
    print $hexNum . "\n";
    print  join "\n", map { unpack ('B*', pack ('H*',$_)) } split ':', 
    $hexNum;

This question is not the same as other entries (specifically Converting hexadecimal numbers in strings to negative numbers, in Perl because it deals specifically with an 8 bit integer, not simply converting to decimal.

Community
  • 1
  • 1
  • 4
    Please show some sample input and the desired output. It's not clear to me what you mean. – PerlDuck Mar 18 '16 at 20:44
  • 1
    This is an exact duplicate -- please see the link in [a3f](http://stackoverflow.com/users/1257035/a3f) comment. – zdim Mar 18 '16 at 22:50

2 Answers2

4

The two's complement of a number $n is just -$n. To limit the result to 8 bits, mask off the rest using (-$n)&0xff.

ikegami
  • 367,544
  • 15
  • 269
  • 518
hobbs
  • 223,387
  • 19
  • 210
  • 288
  • I need to print the result so that I can see the bits flipped. The reason for this is to configure the Tx Load for a Bluetooth Low Energy beacon. For example, I would put in 0xEE and see the 8-bit representation of -18. – Joel Schmidt Mar 21 '16 at 19:28
1
#Hex to Binary and check whether it is signed or unsigned. 
 print "Enter hexidecimal number:";
 chomp ($hexNum = <STDIN>);
 print $hexNum . "\n";
 my $bin_value = sprintf( "%08b", hex( $hexNum ));
 my $msb = ($bin_value & 0x080);
 if($msb){
 print "Unsigned Number\n"}
 else {
 print "Signed Number\n";}

In case you are converting hexadecimal to decimal in that case you need to take 2's complement for which you can use - operator.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Aparna
  • 57
  • 5