How to fix the problem that I can't match the pattern I defined in Lex? - lex

I'm writing a Lex code for scanning Verilog code, and I define a pattern that I want to match. But when I run the code, I find that the pattern I defined won't match. Where did I make a mistake?
I run the code on a Linux workstation. The flex version is 2.5.4.
%option c++
%option noyywrap
%{
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> input_vec; /*To remember which signal is input*/
int input_num = 0; /*To count the # of input signals*/
%}
%x INPUT
var_string [a-z]+
%%
input {
cout << "BEGIN INPUT" << endl;
BEGIN INPUT;
}
[ \n\t\r\f]+
.
<INPUT>{var_string} {
cout << "IN INPUT MATCHING var_string:" << yytext << endl;
input_num++;
input_vec.push_back(yytext);
}
<INPUT>; {BEGIN 0;}
<INPUT>,
<INPUT>[ \n\t\r\f]+
%%
int main(int argc, char* argv[])
{
ifstream input_file("test.v");
FlexLexer* lexer;
lexer = new yyFlexLexer(&input_file, &cout);
while(lexer->yylex()!=0);
cout << "Input Number: " << input_num << endl;
return 0;
}
Here is the Verilog code I want to scan.
module test(a, b, c, sum, carry);
input
a,
b,
c;
output
sum,
carry;
wire
d;
assign
d = (~b & a) | (b & ~a),
sum = (d & c) | (d & ~c),
carry= (a & b) | (b & c) | (a & c);
endmodule
I except that when the Lex code scan a, b, and c in input section, the output will be:
BEGIN INPUT
IN INPUT MATCHING var_string:a
IN INPUT MATCHING var_string:b
IN INPUT MATCHING var_string:c
Input Number: 3
However, the real output is:
BEGIN INPUT
Input Number: 0

Related

Is there a space efficient way to compute the gcd of high exponents?

Basically, I am writing a program that works with large integer values that overflow the cpp integer. I am trying to compute something like: gdc(pow(a, b), c) where a ^ b is the value overflowing the integer limit. Is there a way to do this where I don't have to rely on big integer libraries? If not, are there any recommended big integer libraries?
We can use a property of greatest common divisor that gcd(a, b) = gcd(a % b, b). Hence gcd(pow(a, b), c) = gcd(pow(a, b) % c, c) = gcd(powmod(a, b, c), c), where powmod() is modular exponentiation.
In my C++ code below PowMod() is implemented using exponentiation by squaring approach.
Try it online!
#include <cstdint>
#include <iostream>
using Word = uint32_t;
using DWord = uint64_t;
Word GCD(Word a, Word b) {
Word t = 0;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
return a;
}
Word PowMod(Word a, Word b, Word c) {
Word r = 1;
while (b != 0) {
if (b & 1)
r = (DWord(r) * a) % c;
a = (DWord(a) * a) % c;
b >>= 1;
}
return r;
}
int main() {
Word const
a = 2645680092U, b = 3562429202U, c = 3045001828U,
powmod = PowMod(a, b, c), gcd = GCD(powmod, c);
std::cout << "a = " << a << ", b = " << b
<< ", c = " << c << std::endl;
std::cout << "PowMod(a, b, c) = "
<< powmod << std::endl; // 592284924
std::cout << "GCD(PowMod(a, b, c), c) = "
<< gcd << std::endl; // 1892
}
Output:
a = 2645680092, b = 3562429202, c = 3045001828
PowMod(a, b, c) = 592284924
GCD(PowMod(a, b, c), c) = 1892
which gives correct results, that can be verified through following simple Python program giving same result:
Try it online!
import random, math
random.seed(0)
bits = 32
while True:
c = random.randrange(1 << (bits - 1), 1 << bits)
a = random.randrange(1 << (bits - 1), 1 << bits) % c
b = random.randrange(1 << (bits - 1), 1 << bits)
pm = pow(a, b, c)
gcd = math.gcd(pm, c)
if gcd >= 1000:
print('a =', a, ', b =', b, ', c =', c,
', powmod =', pm, ', gcd =', gcd)
break
Output:
a = 2645680092 , b = 3562429202 , c = 3045001828 ,
powmod = 592284924 , gcd = 1892
If you have GCC/CLang compiler, you can make Word to be 64-bit and DWord to be 128-bit, by changing following lines of code:
using Word = uint64_t;
using DWord = unsigned __int128;
my code supports 32-bit inputs, but after this change you can have 64-bit inputs.
Part 2. Using large integer arithmetics library GMP.
If for some reason you have large input integers then you can use great library GMP for large arithmetics (it supports integer, rational, floating point numbers).
This library has all mathematical operations, including modular exponentiation (PowMod) and some number theoretical functions (including GCD). Also this library is very popular and highly optimized.
In following code I do same things like in me code above, but using only GMP's functions. As an example I use 512-bit integers to show that it can accept large inputs (it can accept even millions of digits):
Try it online!
#include <iostream>
#include <cstdlib>
#include <gmpxx.h>
int main() {
mpz_class const
a("1953143455988359840868749111326065201169739169335107410565117106311318704164104986194255770982854472823807334163384557922525376038346976291413843761504166", 10),
b("5126002245539530470958611905297854592859344951467500786493685495603638740444446597426402800257519403404965463713689509774040138494219032682986554069941558", 10),
c("4396071968291195248321035664209400217968667450140674696924686844534284953565382985421958604880273584922294910355449271193696338132720472184903935323837626", 10);
mpz_class powmod, gcd;
// PowMod
mpz_powm(powmod.get_mpz_t(), a.get_mpz_t(), b.get_mpz_t(), c.get_mpz_t()); // 1632164707041502536171492944083090257113212090861915134477312917063125646194834706890409016008321666479437224930114914370387958138698748075752168351835856
// GCD
mpz_gcd(gcd.get_mpz_t(), powmod.get_mpz_t(), c.get_mpz_t()); // 51842
// Output
std::cout << "PowMod = " << powmod.get_str() << std::endl
<< "GCD = " << gcd.get_str() << std::endl;
}
Output:
PowMod = 1632164707041502536171492944083090257113212090861915134477312917063125646194834706890409016008321666479437224930114914370387958138698748075752168351835856
GCD = 51842
To use GMP library under Linux just install sudo apt install libgmp-dev and compile clang++ -std=c++11 -O2 -lgmp -o main main.cpp.
Using GMP under Windows is a bit more tricky. One way is to build yourself MPIR library which is a Windows friendly clone of GMP. Another way is to install MSYS and use prebuilt GMP from there following these instructions that I wrote in my other answer.

Incorrect output of quadratic equation

I have a problem, and I don't know how to deal with it. I made a simple calculator with few functions. Every option is working fine, but I have problem when it comes to quadratic equation. When I put any numbers the response that I get is "The roots of the equations are : x=1.79599e-307. I don't know to deal with it - can you help me ? I will post parts of my code that includes the problem. Thanks You for any feedback and help!
main:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "kalkulator.cpp"
...
using namespace std;
case 10:
cout<<"\nQuadratic Equation \n";
cout<<"\nSelect number \n";
cin>>a;
cout<<"\nSelect number \n";
cin>>b;
cout<<"\nSelect bumber \n";
cin>>c;
int r;
r=equation(a, b, c, x1, x2);
if (r==0) cout << "\n No roots\n" << endl;
else if (r==1) cout << "\n 1 root x = " << x1 << endl;
else if (r==2) cout << "\n 2 roots x1 = " << x1 << " and x2 = " << x2 << endl;
break;
kalkulator.cpp
#include "kalkulator.h"
using namespace std;
...
double equation(double a, double b, double c, double x1, double
x2)
{
double delta=b*b-4*a*c;
if (delta<0.0)
{
return 0;}
if (delta==0.0)
{
x1=-b/(2*a);
return 1;}
else
{
delta=sqrt(delta);
x1==(-b-delta)/(2*a);
x2==(-b+delta)/(2*a);
return 2;}}
kalkulator.h
#ifndef kalkulator_H
#define kalkulator_H
class kalkulator
{
private:
double a;
double b;
double c;
double x1;
double x2;
public:
double equation(double, double, double, double, double);
};
#endif
If you want to set x1 and x2 through the supplied parameters, you need to pass them by reference:
double equation(double, double, double, double&, double&);
and
double equation(double a, double b, double c, double & x1, double & x2)
Also, in the last lines of your code, "x1==" and "x2==" should be "x1=" and "x2=".

How To Create and Verify Blind RSA Signatures With Crypto++?

I've read through the whitepapers and specifications relating to blind signatures which I've been able to come across, inclusive of the Wikipedia entries, but these tend to focus on the mathematical theory behind it.
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Yes. The Crypto++ wiki has a section on blind signatures for RSA at Raw RSA | RSA Blind Signature. Below is the code taken from the wiki.
Crypto++ lacks blind signature classes. The method below follows the basic algorithm as detailed at Blind Signatures. However, it differs from Wikipedia by applying the s(s'(x)) = x cross-check. The cross-check was present in Chaum's original paper, but it is missing from the wiki article. A second difference from Chaum's paper and wikipedia is, the code below uses H(m) rather than m. That's due to Rabin in 1979.
As far as we know there is no standard covering the signature scheme. The lack of standardization will surely cause interop problems. For example, the code below uses SHA256 to hash the message to be signed, while RSA Blind Signature Scheme for golang uses full domain hashing. Also see Is there a standard padding/format for RSA Blind Signatures? on Crypto.SE.
You may want to apply a padding function first per Usability of padding scheme in blinded RSA signature? or RSA blind signatures in practice.
#include "cryptlib.h"
#include "integer.h"
#include "nbtheory.h"
#include "osrng.h"
#include "rsa.h"
#include "sha.h"
using namespace CryptoPP;
#include <iostream>
#include <stdexcept>
using std::cout;
using std::endl;
using std::runtime_error;
int main(int argc, char* argv[])
{
// Bob artificially small key pair
AutoSeededRandomPool prng;
RSA::PrivateKey privKey;
privKey.GenerateRandomWithKeySize(prng, 64);
RSA::PublicKey pubKey(privKey);
// Convenience
const Integer& n = pubKey.GetModulus();
const Integer& e = pubKey.GetPublicExponent();
const Integer& d = privKey.GetPrivateExponent();
// Print params
cout << "Pub mod: " << std::hex << pubKey.GetModulus() << endl;
cout << "Pub exp: " << std::hex << e << endl;
cout << "Priv mod: " << std::hex << privKey.GetModulus() << endl;
cout << "Priv exp: " << std::hex << d << endl;
// For sizing the hashed message buffer. This should be SHA256 size.
const size_t SIG_SIZE = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
// Scratch
SecByteBlock buff1, buff2, buff3;
// Alice original message to be signed by Bob
SecByteBlock orig((const byte*)"secret", 6);
Integer m(orig.data(), orig.size());
cout << "Message: " << std::hex << m << endl;
// Hash message per Rabin (1979)
buff1.resize(SIG_SIZE);
SHA256 hash1;
hash1.CalculateTruncatedDigest(buff1, buff1.size(), orig, orig.size());
// H(m) as Integer
Integer hm(buff1.data(), buff1.size());
cout << "H(m): " << std::hex << hm << endl;
// Alice blinding
Integer r;
do {
r.Randomize(prng, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(r, n));
// Blinding factor
Integer b = a_exp_b_mod_c(r, e, n);
cout << "Random: " << std::hex << b << endl;
// Alice blinded message
Integer mm = a_times_b_mod_c(hm, b, n);
cout << "Blind msg: " << std::hex << mm << endl;
// Bob sign
Integer ss = privKey.CalculateInverse(prng, mm);
cout << "Blind sign: " << ss << endl;
// Alice checks s(s'(x)) = x. This is from Chaum's paper
Integer c = pubKey.ApplyFunction(ss);
cout << "Check sign: " << c << endl;
if (c != mm)
throw runtime_error("Alice cross-check failed");
// Alice remove blinding
Integer s = a_times_b_mod_c(ss, r.InverseMod(n), n);
cout << "Unblind sign: " << s << endl;
// Eve verifies
Integer v = pubKey.ApplyFunction(s);
cout << "Verify: " << std::hex << v << endl;
// Convert to a string
size_t req = v.MinEncodedSize();
buff2.resize(req);
v.Encode(&buff2[0], buff2.size());
// Hash message per Rabin (1979)
buff3.resize(SIG_SIZE);
SHA256 hash2;
hash2.CalculateTruncatedDigest(buff3, buff3.size(), orig, orig.size());
// Constant time compare
bool equal = buff2.size() == buff3.size() && VerifyBufsEqual(
buff2.data(), buff3.data(), buff3.size());
if (!equal)
throw runtime_error("Eve verified failed");
cout << "Verified signature" << endl;
return 0;
}
Here is the result of building and running the program:
$ g++ blind.cxx ./libcryptopp.a -o blind.exe
$ ./blind.exe
Pub mod: b55dc5e79993680fh
Pub exp: 11h
Priv mod: b55dc5e79993680fh
Priv exp: 1b4fc70ff2e97f1h
Message: 736563726574h
H(m): 2bb80d537b1da3e3h
Random: 72dd6819f0fc5e5fh
Blinded msg: 27a2e2e5e6f4fbfh
Blind sign: 84e7039495bf0570h
Check sign: 27a2e2e5e6f4fbfh
Unblind sign: 61054203e843f380h
Verify: 2bb80d537b1da3e3h
Verified signature

how to convert variable type integer to double

I want to convert integers to double in the following piece of code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a , b;
double c;
cout<<"Enter two integers: ";
cin>>a>>b;
try
{
if (b == 0)
throw 0;
}
catch (int a)
{
cout<<"You made a division by zero?"<<endl<<a;
}
c = static_cast<double>(a/b);
cout<<"The division is: "<<fixed<<setprecision(2)<<c;
}
How to change the code to output the double value?
As mentioned you should cast not a result of division but variables itself, to get double value. All three options works.
int a, b;
double c;
std::cout << "Enter two integers: ";
std::cin >> a >> b;
try
{
if (b == 0)
throw 0;
}
catch (int a)
{
std::cout << "You made a division by zero?" << std::endl << a;
}
c = static_cast<double>(a) / b;
c = a / static_cast<double>(b);
c = static_cast<double>(a) / static_cast<double>(b);
std::cout << "The division is: " << std::fixed << std::setprecision(2) << c;
std::cin >> a >> b;
You are casting the result of the division, you should cast the operands instead.
Don't use an exception to catch a condition that you already catch using a simple if. Just use the if, and use an else to skip the division if the second operand is zero.
int a , b;
double c;
cout<<"Enter two integers: ";
cin>>a>>b;
if (b == 0) {
cout<<"You made a division by zero?"<<endl;
} else {
c = static_cast<double>(a) / static_cast<double>(b);
cout<<"The division is: "<<fixed<<setprecision(2)<<c;
}

Have problem with lex

My lex as follows:
LNUM [0-9]+
DNUM([0-9]*"."[0-9]+)|([0-9]+"."[0-9]*)
%%
{LNUM} {
printf("\t");ECHO;printf("\r\n");
}
{DNUM} {
printf("\t");ECHO;printf("\r\n");
}
But it turns out that it can only match numbers like 4.12 .2,not 42,45. etc.(those indented are matched)
Output:
1.
1.
.1
.1
12
12
My target is to match both integers and float numbers.
Can anyone here tell me what's wrong above?
Late answer to your question... but for what it's worth, I tried replacing the * you had in the original lex file (the second pattern for DNUM) with a + (because that ensures that you at least have one digit to the right of the decimal point in order for the number to be counted as a decimal...) and it seems to work for me, at least. Hope this helps someone in the future.
lex file:
%{
#include <iostream>
using namespace std;
%}
LNUM [0-9]+
DNUM ([0-9]*"."[0-9]+)|([0-9]+"."[0-9]+)
%option noyywrap
%%
{LNUM}* { cout << "lnum: " << yytext << endl; }
{DNUM}* { cout << "dnum: " << yytext << endl; }
%%
int main(int argc, char ** argv)
{
yylex();
return 0;
}
example input (on command line):
$ echo "4.12 .2 42 45. " | ./lexer
dnum: 4.12
dnum: .2
lnum: 42
lnum: 45.