ClearAll["Global`*"]

(*定义CDAC的基本信息*)
bits=10;vref=1;
(*创建CDAC的电容阵列*)
capArray=Join[Table[2^(bits-n),{n,1,bits,1}],{1}];
(*创建所有输出二进制编码数组*)
codes=Table[IntegerDigits[code,2,bits],{code,0,2^bits-1,1}];
(*创建Table存储每个code的每一次comp的能量E*)
codeLoopcompLoopE=Table[Table[0,bits],2^bits];


For[decCode=0,decCode<2^bits,decCode++,
{
code=codes[[decCode+1]];
For[cmpBit=1,cmpBit<=bits,cmpBit++,
{If[cmpBit==1,
{lastCode=Join[Table[0,bits],{0}];currentCode=Join[{1},Table[0,bits-1],{0}];}
];
If[cmpBit>1,
{lastCode=code;
lastCode[[cmpBit-1]]=1;
lastCode[[cmpBit;;bits]]=Table[0,bits-cmpBit+1];
currentCode=lastCode;
currentCode[[cmpBit-1]]=code[[cmpBit-1]];
currentCode[[cmpBit]]=1;
lastCode=Join[lastCode,{0}];
currentCode=Join[currentCode,{0}];
}];

(*正向输入端CDAC电位状态 & VREF输出的电荷*)
posLastCode=lastCode;
posCurrentCode=currentCode;
posBotCodeChange=posCurrentCode-posLastCode;
posBotVoltageChangeArray=posBotCodeChange*vref;
posTopVoltageChange=Sum[(posBotCodeChange*capArray)[[i]],{i,1,bits}]/2^bits;
posTopVoltageChangeArray=Table[posTopVoltageChange,bits+1];
posCurrentVrefCapArray=posCurrentCode*capArray;
posQ=Sum[(posCurrentVrefCapArray*(posBotVoltageChangeArray-posTopVoltageChangeArray))[[i]],{i,1,bits+1}];

(*负向输入端CDAC电位状态 & VREF输出的电荷*)
negLastCode=Map[If[#==1,0,1]&,lastCode];
negCurrentCode=Map[If[#==1,0,1]&,currentCode];
negBotCodeChange=negCurrentCode-negLastCode;
negBotVoltageChangeArray=negBotCodeChange*vref;
negTopVoltageChange=Sum[(negBotCodeChange*capArray)[[i]],{i,1,bits}]/2^bits;
negTopVoltageChangeArray=Table[negTopVoltageChange,bits+1];
negCurrentVrefCapArray=negCurrentCode*capArray;
negQ=Sum[(posCurrentVrefCapArray*(posBotVoltageChangeArray-posTopVoltageChangeArray))[[i]],{i,1,bits+1}];

(*打印中间状态*)
(*Print["code=",code," comBit=",cmpBit," pos=",posLastCode,posCurrentCode,posQ," neg=",negLastCode,negCurrentCode,negQ];*)

(*单次CDAC提供的能量=电荷×VREF*)
codeLoopcompLoopE[[decCode+1,cmpBit]]=(posQ+negQ)*vref;
}];
}];

codeLoopcompLoopE;
codeLoopE=Map[Total[#]&,codeLoopcompLoopE];
codeLoop=Table[i,{i,0,2^bits-1}];
codeLoopVScodeLoopE=Transpose[{codeLoop,codeLoopE}];

Print["Average Energy=",Mean[codeLoopE]//N];
ListLinePlot[codeLoopVScodeLoopE,PlotRange->{{0,1024},{600,1800}},Ticks->{Table[i,{i,0,1024,2^7}],Table[200*i,{i,2,10}]},GridLines->{Table[i,{i,0,1024,2^7}],Table[200*i,{i,2,10}]}]