Rich
Rich

Reputation: 1185

How to do SystemVerilog-style bit vector slice assignment in C++?

I am porting some SystemVerilog code to SystemC/C++. I am using std::bitset to represent bit vectors, but I can see already it falls short of providing methods to access a slice.

For example, if I want to set reg1 to bits 4-8 of reg2 with the SystemVerilog code:

bit [3:0] reg1;
bit [15:0] reg2;
reg1 = reg2[7:4];

How could I do this with std::bitset?

bitset<4> reg1;
bitset<16> reg2;
reg1[0] = reg2[4];
reg1[1] = reg2[5];
reg1[2] = reg2[6];
reg1[3] = reg2[7];

Is there a better way?

Upvotes: 4

Views: 2210

Answers (2)

jclin
jclin

Reputation: 2559

Now you are using SystemC, why don't you use sc_bv<> to represent HDL signals natively? Because SystemC has a set of data type to represent HDL bit/logic-wise and word logical operators, it should be more easy to mapping SystemVerilog/Verilog data types to C/C++ code.

sc_bv<4> reg1;
sc_bv<16> reg2;
reg1 = reg2.range(7,4);

Upvotes: 5

PiotrNycz
PiotrNycz

Reputation: 24412

If your want to operate on bitsets - then use to_string function:

bitset<4> reg1;
bitset<16> reg2;
reg1 = bitset<4>(reg2.to_string().substr(4,4));

This is not very efficient way, but should work.

If you do not have bitsets bigger than 32 or 64 bits - then use version with to_ulong or to_ullong - it should be more efficient.

Also consider to use std::vector<bool> instead of std::bitset<>. Folks here have tendency to make downvote every time they see std::vector<bool>, but it could be more efficient here:

vector<bool> reg1(4);
vector<bool> reg2(16);
reg1.assign(reg2.begin() + 4, reg2.begin() + 8);

Upvotes: 4

Related Questions