What if I want to add or replace fixed length values in the middle of a field

For example, I have 256bit headers and I want to replace them with local values (0xffA1) at 0-31bit. How does this work with P4_16.

Here the 256bit is fixed, i.e

header h{

bit<256> a1;

}

I want to replace a1<offset,length> with some other value

If the bits you want to change within a1 are at a compile-time constant range of bit positions, you can do an assignment like hdr.h1.a1[127:120] = 15;. For a field with type bit<W> in a header, the first bit of that field in the packet is bit position W-1, and the last is bit position 0.

If the bits you want to change within a1 are at a run-time variable range of bit positions, the only way I know is to have separate assignments for each possible constant range of bits you want to assign in different cases, and then use an if/then/else-if statement or a table to pick between them at run time.

If you have many different cases you want to select between at run time, the kind of code mentioned in the previous paragraph can be quite repetitive and tedious to write by hand. Often it is easier to write a little program in another language that prints out the repetitive P4 source code. Here is an article with some examples of doing that: p4-guide/README.md at master · jafingerhut/p4-guide · GitHub