Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

binary conversion

Status
Not open for further replies.

HPD79

Technical User
Jun 9, 2009
2
US
Hi Can someone help me to figure out why i am not gettiong the right output. on the screen it prints fine but not in the file

Thanks
######################################################
#!/usr/local/bin/perl

open(DAT, "datafile.txt") ||die("Could not open file!");

open(FILE, ">output.txt") || die("Could not open file!");

@read_data=<DAT>;

foreach $variable(@read_data)
{

# print "$variable\n";
binary_2_decimal($variable);
}
sub binary_2_decimal{
my $int = shift;

## constant = 10000000000000000000000000000000
my $and = 0x80000000;

## for each bit
for(1..32){
## if the bit is set, print 1
if( $int & $and ){
print "1";
}
## if the bit is not set, print 0
else{
print "0";
}
## shift the constant using right shift
$and = $and >> 1;
}
print "\n";
print FILE "$and\n";

}
close(DAT);
close(FILE);
####################################################
 
What output are you expecting to the file?

Do you want to print the same text to the file as is printing to the console?

What does "datfile.txt" contain?

At first glance it looks like you are doing a lot of unnecessary work shifting bits when printf will convert the numbers to binary representation just fine.
 
i am takeing data file which has
1
2
3
etc

and converting to the binary output file which will have
0000001
0000010
0000011
etc
 
Printf will perform decimal to binary conversions without any extra code:
Code:
#!/usr/local/bin/perl
##open(DAT, "<", "datafile.txt") || die("Could not open file!\n$!\n"); # uncomment when ready
open(FILE, ">", "output.txt") || die("Could not open file!\n$!\n");

while (<DATA>) # change to 'DAT' file when testing is done
{
   printf FILE "%032b\n", $_;
}

__DATA__
1
2
3

Output:
Code:
00000000000000000000000000000001
00000000000000000000000000000010
00000000000000000000000000000011
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top