WeixiangYan/CodeTransOcean huggingface dataset:
Task: Text processing_2


C++: #include <boost/regex.hpp>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cstdlib>
#include <algorithm>
using namespace std ;

boost::regex e ( "\\s+" ) ; 

int main( int argc , char *argv[ ] ) { 
   ifstream infile( argv[ 1 ] ) ; 
   vector<string> duplicates ;
   set<string> datestamps ; 
   if ( ! infile.is_open( ) ) { 
      cerr << "Can't open file " << argv[ 1 ] << '\n' ;
      return 1 ; 
   }   
   int all_ok = 0  ;
   int pattern_ok = 0 ; 
   while ( infile ) { 
      string eingabe ;
      getline( infile , eingabe ) ;
      boost::sregex_token_iterator i ( eingabe.begin( ), eingabe.end( ) , e , -1 ), j  ;
      vector<string> fields( i, j ) ;
      if ( fields.size( ) == 49 ) 
         pattern_ok++ ;
      else
         cout << "Format not ok!\n" ;
      if ( datestamps.insert( fields[ 0 ] ).second ) { 
         int howoften = ( fields.size( ) - 1 ) / 2 ;
                                                    
         for ( int n = 1 ; atoi( fields[ 2 * n ].c_str( ) ) >= 1 ; n++ ) {
            if ( n == howoften ) {
               all_ok++ ;
               break ;
            }
         }
      }
      else {
         duplicates.push_back( fields[ 0 ] ) ;
      }
   }
   infile.close( ) ;
   cout << "The following " << duplicates.size() << " datestamps were duplicated:\n" ;
   copy( duplicates.begin( ) , duplicates.end( ) ,
         ostream_iterator<string>( cout , "\n" ) ) ;
   cout << all_ok << " records were complete and ok!\n" ;
   return 0 ;
}





PHP: $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
    $buffer = fgets($handle);
	$line = preg_replace('/\s+/',' ',$buffer);
	$line = explode(' ',trim($line));
	$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
	$valpattern = '/^\d+\.{1}\d{3}$/';
	$flagpattern = '/^[1-9]{1}$/';
	
	if(count($line) != 49) $missformcount++;
	if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
	else $dates[$totalcount+1] = $check[0];
	
	$errcount = 0;
	for($i=1;$i<count($line);$i++){
		if($i%2!=0){
			if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
		}else{
			if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
		}
	}
	if($errcount != 0) $missformcount++;
	$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
	echo $val . ' at Line : ' . $key . '<br>';
}
Task: Text processing_2




Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	filename   = "readings.txt"
	readings   = 24             
	fields     = readings*2 + 1 
	dateFormat = "2006-01-02"
)

func main() {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	var allGood, uniqueGood int
	
	
	m := make(map[time.Time]bool)
	s := bufio.NewScanner(file)
	for s.Scan() {
		f := strings.Fields(s.Text())
		if len(f) != fields {
			log.Fatal("unexpected format,", len(f), "fields.")
		}
		ts, err := time.Parse(dateFormat, f[0])
		if err != nil {
			log.Fatal(err)
		}
		good := true
		for i := 1; i < fields; i += 2 {
			flag, err := strconv.Atoi(f[i+1])
			if err != nil {
				log.Fatal(err)
			}
			if flag > 0 { 
				_, err := strconv.ParseFloat(f[i], 64)
				if err != nil {
					log.Fatal(err)
				}
			} else { 
				good = false
			}
		}
		if good {
			allGood++
		}
		previouslyGood, seen := m[ts]
		if seen {
			fmt.Println("Duplicate datestamp:", f[0])
		}
		m[ts] = previouslyGood || good
		if !previouslyGood && good {
			uniqueGood++
		}
	}
	if err := s.Err(); err != nil {
		log.Fatal(err)
	}

	fmt.Println("\nData format valid.")
	fmt.Println(allGood, "records with good readings for all instruments.")
	fmt.Println(uniqueGood,
		"unique dates with good readings for all instruments.")
}



PHP: $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
    $buffer = fgets($handle);
	$line = preg_replace('/\s+/',' ',$buffer);
	$line = explode(' ',trim($line));
	$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
	$valpattern = '/^\d+\.{1}\d{3}$/';
	$flagpattern = '/^[1-9]{1}$/';
	
	if(count($line) != 49) $missformcount++;
	if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
	else $dates[$totalcount+1] = $check[0];
	
	$errcount = 0;
	for($i=1;$i<count($line);$i++){
		if($i%2!=0){
			if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
		}else{
			if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
		}
	}
	if($errcount != 0) $missformcount++;
	$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
	echo $val . ' at Line : ' . $key . '<br>';
}
Task: Text processing_2





Java: import java.util.*;
import java.util.regex.*;
import java.io.*;

public class DataMunging2 {

    public static final Pattern e = Pattern.compile("\\s+");

    public static void main(String[] args) {
        try {
            BufferedReader infile = new BufferedReader(new FileReader(args[0]));
            List<String> duplicates = new ArrayList<String>();
            Set<String> datestamps = new HashSet<String>(); 

            String eingabe;
            int all_ok = 0;
            while ((eingabe = infile.readLine()) != null) { 
                String[] fields = e.split(eingabe); 
                if (fields.length != 49) 
                    System.out.println("Format not ok!");
                if (datestamps.add(fields[0])) { 
                    int howoften = (fields.length - 1) / 2 ; 
                                                             
                    for (int n = 1; Integer.parseInt(fields[2*n]) >= 1; n++) {
                        if (n == howoften) {
                            all_ok++ ;
                            break ;
                        }
                    }
                } else {
                    duplicates.add(fields[0]); 
                }
            }
            infile.close();
            System.out.println("The following " + duplicates.size() + " datestamps were duplicated:");
            for (String x : duplicates)
                System.out.println(x);
            System.out.println(all_ok + " records were complete and ok!");
        } catch (IOException e) {
            System.err.println("Can't open file " + args[0]);
            System.exit(1);
        }
    }
}


PHP: $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
    $buffer = fgets($handle);
	$line = preg_replace('/\s+/',' ',$buffer);
	$line = explode(' ',trim($line));
	$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
	$valpattern = '/^\d+\.{1}\d{3}$/';
	$flagpattern = '/^[1-9]{1}$/';
	
	if(count($line) != 49) $missformcount++;
	if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
	else $dates[$totalcount+1] = $check[0];
	
	$errcount = 0;
	for($i=1;$i<count($line);$i++){
		if($i%2!=0){
			if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
		}else{
			if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
		}
	}
	if($errcount != 0) $missformcount++;
	$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
	echo $val . ' at Line : ' . $key . '<br>';
}
Task: Text processing_2






PHP: $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
    $buffer = fgets($handle);
	$line = preg_replace('/\s+/',' ',$buffer);
	$line = explode(' ',trim($line));
	$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
	$valpattern = '/^\d+\.{1}\d{3}$/';
	$flagpattern = '/^[1-9]{1}$/';
	
	if(count($line) != 49) $missformcount++;
	if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
	else $dates[$totalcount+1] = $check[0];
	
	$errcount = 0;
	for($i=1;$i<count($line);$i++){
		if($i%2!=0){
			if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
		}else{
			if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
		}
	}
	if($errcount != 0) $missformcount++;
	$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
	echo $val . ' at Line : ' . $key . '<br>';
}


Python: import re
import zipfile
import StringIO

def munge2(readings):

   datePat = re.compile(r'\d{4}-\d{2}-\d{2}')
   valuPat = re.compile(r'[-+]?\d+\.\d+')
   statPat = re.compile(r'-?\d+')
   allOk, totalLines = 0, 0
   datestamps = set([])
   for line in readings:
      totalLines += 1
      fields = line.split('\t')
      date = fields[0]
      pairs = [(fields[i],fields[i+1]) for i in range(1,len(fields),2)]

      lineFormatOk = datePat.match(date) and \
         all( valuPat.match(p[0]) for p in pairs ) and \
         all( statPat.match(p[1]) for p in pairs )
      if not lineFormatOk:
         print 'Bad formatting', line
         continue
		
      if len(pairs)!=24 or any( int(p[1]) < 1 for p in pairs ):
         print 'Missing values', line
         continue

      if date in datestamps:
         print 'Duplicate datestamp', line
         continue
      datestamps.add(date)
      allOk += 1

   print 'Lines with all readings: ', allOk
   print 'Total records: ', totalLines



readings = open('readings.txt','r')
munge2(readings)
Task: Text processing_2






PHP: $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
    $buffer = fgets($handle);
	$line = preg_replace('/\s+/',' ',$buffer);
	$line = explode(' ',trim($line));
	$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
	$valpattern = '/^\d+\.{1}\d{3}$/';
	$flagpattern = '/^[1-9]{1}$/';
	
	if(count($line) != 49) $missformcount++;
	if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
	else $dates[$totalcount+1] = $check[0];
	
	$errcount = 0;
	for($i=1;$i<count($line);$i++){
		if($i%2!=0){
			if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
		}else{
			if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
		}
	}
	if($errcount != 0) $missformcount++;
	$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
	echo $val . ' at Line : ' . $key . '<br>';
}



VB: Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
			"\readings.txt",1)
Set objDateStamp = CreateObject("Scripting.Dictionary")

Total_Records = 0
Valid_Records = 0
Duplicate_TimeStamps = ""

Do Until objFile.AtEndOfStream
	line = objFile.ReadLine
	If line <> "" Then
		token = Split(line,vbTab)
		If objDateStamp.Exists(token(0)) = False Then
			objDateStamp.Add token(0),""
			Total_Records = Total_Records + 1
			If IsValid(token) Then
				Valid_Records = Valid_Records + 1
			End If
		Else
			Duplicate_TimeStamps = Duplicate_TimeStamps & token(0) & vbCrLf
			Total_Records = Total_Records + 1
		End If
	End If 	
Loop

Function IsValid(arr)
	IsValid = True
	Bad_Readings = 0
	n = 1
	Do While n <= UBound(arr)
		If n + 1 <= UBound(arr) Then
			If CInt(arr(n+1)) < 1 Then
				Bad_Readings = Bad_Readings + 1	
			End If 
		End If
		n = n + 2
	Loop
	If Bad_Readings > 0 Then
		IsValid = False
	End If
End Function

WScript.StdOut.Write "Total Number of Records = " & Total_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Total Valid Records = " & Valid_Records
WScript.StdOut.WriteLine
WScript.StdOut.Write "Duplicate Timestamps:"
WScript.StdOut.WriteLine
WScript.StdOut.Write Duplicate_TimeStamps
WScript.StdOut.WriteLine

objFile.Close
Set objFSO = Nothing
Task: RSA code

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main(void)
{
    mpz_t n, d, e, pt, ct;

    mpz_init(pt);
    mpz_init(ct);
    mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10);
    mpz_init_set_str(e, "65537", 10);
    mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10);

    const char *plaintext = "Rossetta Code";
    mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);

    if (mpz_cmp(pt, n) > 0)
        abort();

    mpz_powm(ct, pt, e, n);
    gmp_printf("Encoded:   %Zd\n", ct);

    mpz_powm(pt, ct, d, n);
    gmp_printf("Decoded:   %Zd\n", pt);

    char buffer[64];
    mpz_export(buffer, NULL, 1, 1, 0, 0, pt);
    printf("As String: %s\n", buffer);

    mpz_clears(pt, ct, n, e, d, NULL);
    return 0;
}



C#: using System;
using System.Numerics;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
        BigInteger e = 65537;
        BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");

        const string plaintextstring = "Hello, Rosetta!";
        byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring);
        BigInteger pt = new BigInteger(plaintext);
        if (pt > n)
            throw new Exception();

        BigInteger ct = BigInteger.ModPow(pt, e, n);
        Console.WriteLine("Encoded:  " + ct);

        BigInteger dc = BigInteger.ModPow(ct, d, n);
        Console.WriteLine("Decoded:  " + dc);

        string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray());
        Console.WriteLine("As ASCII: " + decoded);
    }
}
Task: RSA code

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main(void)
{
    mpz_t n, d, e, pt, ct;

    mpz_init(pt);
    mpz_init(ct);
    mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10);
    mpz_init_set_str(e, "65537", 10);
    mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10);

    const char *plaintext = "Rossetta Code";
    mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);

    if (mpz_cmp(pt, n) > 0)
        abort();

    mpz_powm(ct, pt, e, n);
    gmp_printf("Encoded:   %Zd\n", ct);

    mpz_powm(pt, ct, d, n);
    gmp_printf("Decoded:   %Zd\n", pt);

    char buffer[64];
    mpz_export(buffer, NULL, 1, 1, 0, 0, pt);
    printf("As String: %s\n", buffer);

    mpz_clears(pt, ct, n, e, d, NULL);
    return 0;
}




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    var n, e, d, bb, ptn, etn, dtn big.Int
    pt := "Rosetta Code"
    fmt.Println("Plain text:            ", pt)

    
    
    
    n.SetString("9516311845790656153499716760847001433441357", 10)
    e.SetString("65537", 10)
    d.SetString("5617843187844953170308463622230283376298685", 10)

    
    for _, b := range []byte(pt) {
        ptn.Or(ptn.Lsh(&ptn, 8), bb.SetInt64(int64(b)))
    }
    if ptn.Cmp(&n) >= 0 {
        fmt.Println("Plain text message too long")
        return
    }
    fmt.Println("Plain text as a number:", &ptn)

    
    etn.Exp(&ptn, &e, &n)
    fmt.Println("Encoded:               ", &etn)

    
    dtn.Exp(&etn, &d, &n)
    fmt.Println("Decoded:               ", &dtn)

    
    var db [16]byte
    dx := 16
    bff := big.NewInt(0xff)
    for dtn.BitLen() > 0 {
        dx--
        db[dx] = byte(bb.And(&dtn, bff).Int64())
        dtn.Rsh(&dtn, 8)
    }
    fmt.Println("Decoded number as text:", string(db[dx:]))
}
Task: RSA code

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main(void)
{
    mpz_t n, d, e, pt, ct;

    mpz_init(pt);
    mpz_init(ct);
    mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10);
    mpz_init_set_str(e, "65537", 10);
    mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10);

    const char *plaintext = "Rossetta Code";
    mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);

    if (mpz_cmp(pt, n) > 0)
        abort();

    mpz_powm(ct, pt, e, n);
    gmp_printf("Encoded:   %Zd\n", ct);

    mpz_powm(pt, ct, d, n);
    gmp_printf("Decoded:   %Zd\n", pt);

    char buffer[64];
    mpz_export(buffer, NULL, 1, 1, 0, 0, pt);
    printf("As String: %s\n", buffer);

    mpz_clears(pt, ct, n, e, d, NULL);
    return 0;
}








VB: Imports System
Imports System.Numerics
Imports System.Text

Module Module1
    Sub Main()
        Dim n As BigInteger = BigInteger.Parse("9516311845790656153499716760847001433441357")
        Dim e As BigInteger = 65537
        Dim d As BigInteger = BigInteger.Parse("5617843187844953170308463622230283376298685")
        Dim plainTextStr As String = "Hello, Rosetta!"
        Dim plainTextBA As Byte() = ASCIIEncoding.ASCII.GetBytes(plainTextStr)
        Dim pt As BigInteger = New BigInteger(plainTextBA)
        If pt > n Then Throw New Exception() 
        Dim ct As BigInteger = BigInteger.ModPow(pt, e, n)
        Console.WriteLine(" Encoded: " & ct.ToString("X"))
        Dim dc As BigInteger = BigInteger.ModPow(ct, d, n)
        Console.WriteLine(" Decoded: " & dc.ToString("X"))
        Dim decoded As String = ASCIIEncoding.ASCII.GetString(dc.ToByteArray())
        Console.WriteLine("As ASCII: " & decoded)
    End Sub
End Module
Task: RSA code



C#: using System;
using System.Numerics;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
        BigInteger e = 65537;
        BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");

        const string plaintextstring = "Hello, Rosetta!";
        byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring);
        BigInteger pt = new BigInteger(plaintext);
        if (pt > n)
            throw new Exception();

        BigInteger ct = BigInteger.ModPow(pt, e, n);
        Console.WriteLine("Encoded:  " + ct);

        BigInteger dc = BigInteger.ModPow(ct, d, n);
        Console.WriteLine("Decoded:  " + dc);

        string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray());
        Console.WriteLine("As ASCII: " + decoded);
    }
}


Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    var n, e, d, bb, ptn, etn, dtn big.Int
    pt := "Rosetta Code"
    fmt.Println("Plain text:            ", pt)

    
    
    
    n.SetString("9516311845790656153499716760847001433441357", 10)
    e.SetString("65537", 10)
    d.SetString("5617843187844953170308463622230283376298685", 10)

    
    for _, b := range []byte(pt) {
        ptn.Or(ptn.Lsh(&ptn, 8), bb.SetInt64(int64(b)))
    }
    if ptn.Cmp(&n) >= 0 {
        fmt.Println("Plain text message too long")
        return
    }
    fmt.Println("Plain text as a number:", &ptn)

    
    etn.Exp(&ptn, &e, &n)
    fmt.Println("Encoded:               ", &etn)

    
    dtn.Exp(&etn, &d, &n)
    fmt.Println("Decoded:               ", &dtn)

    
    var db [16]byte
    dx := 16
    bff := big.NewInt(0xff)
    for dtn.BitLen() > 0 {
        dx--
        db[dx] = byte(bb.And(&dtn, bff).Int64())
        dtn.Rsh(&dtn, 8)
    }
    fmt.Println("Decoded number as text:", string(db[dx:]))
}
Task: RSA code



C#: using System;
using System.Numerics;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
        BigInteger e = 65537;
        BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");

        const string plaintextstring = "Hello, Rosetta!";
        byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring);
        BigInteger pt = new BigInteger(plaintext);
        if (pt > n)
            throw new Exception();

        BigInteger ct = BigInteger.ModPow(pt, e, n);
        Console.WriteLine("Encoded:  " + ct);

        BigInteger dc = BigInteger.ModPow(ct, d, n);
        Console.WriteLine("Decoded:  " + dc);

        string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray());
        Console.WriteLine("As ASCII: " + decoded);
    }
}



Java: public static void main(String[] args) {
    
    BigInteger n = new BigInteger("9516311845790656153499716760847001433441357");
    BigInteger e = new BigInteger("65537");
    BigInteger d = new BigInteger("5617843187844953170308463622230283376298685");
    Charset c = Charsets.UTF_8;
    String plainText = "Rosetta Code";
    System.out.println("PlainText : " + plainText);
    byte[] bytes = plainText.getBytes();
    BigInteger plainNum = new BigInteger(bytes);
    System.out.println("As number : " + plainNum);
    BigInteger Bytes = new BigInteger(bytes);
    if (Bytes.compareTo(n) == 1) {
        System.out.println("Plaintext is too long");
        return;
    }
    BigInteger enc = plainNum.modPow(e, n);
    System.out.println("Encoded: " + enc);
    BigInteger dec = enc.modPow(d, n);
    System.out.println("Decoded: " + dec);
    String decText = new String(dec.toByteArray(), c);
    System.out.println("As text: " + decText);
}
Task: RSA code



C#: using System;
using System.Numerics;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
        BigInteger e = 65537;
        BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");

        const string plaintextstring = "Hello, Rosetta!";
        byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring);
        BigInteger pt = new BigInteger(plaintext);
        if (pt > n)
            throw new Exception();

        BigInteger ct = BigInteger.ModPow(pt, e, n);
        Console.WriteLine("Encoded:  " + ct);

        BigInteger dc = BigInteger.ModPow(ct, d, n);
        Console.WriteLine("Decoded:  " + dc);

        string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray());
        Console.WriteLine("As ASCII: " + decoded);
    }
}





Python: import binascii

n = 9516311845790656153499716760847001433441357    
e = 65537
d = 5617843187844953170308463622230283376298685

message='Rosetta Code!'
print('message                 ', message)

hex_data   = binascii.hexlify(message.encode())
print('hex data                ', hex_data)

plain_text = int(hex_data, 16)
print('plain text integer      ', plain_text)

if plain_text > n:
  raise Exception('plain text too large for key')

encrypted_text = pow(plain_text,     e, n)
print('encrypted text integer  ', encrypted_text)

decrypted_text = pow(encrypted_text, d, n)
print('decrypted text integer  ', decrypted_text)

print('message                 ', binascii.unhexlify(hex(decrypted_text)[2:]).decode())