private static void SecondaryDataCheckEven(int eccLength, int[] maxiCodewords) { // Handles error correction of even characters in secondary. int dataLength = 68; if (eccLength == 20) { dataLength = 84; } byte[] dataCodewords = new byte[dataLength]; byte[] eccCodewords = new byte[eccLength]; for (int j = 0; j < dataLength + 1; j++) { if ((j & 1) == 0) // Even { dataCodewords[j / 2] = (byte)maxiCodewords[j + 20]; } } ReedSolomon.RSInitialise(0x43, eccLength, 1); ReedSolomon.RSEncode(dataLength / 2, dataCodewords, eccCodewords); for (int j = 0; j < eccLength; j++) { maxiCodewords[dataLength + (2 * j) + 20] = eccCodewords[eccLength - 1 - j]; } }
//byte[] msg = new byte[223]; static void Main(string[] args) { ReedSolomon _rs = new ReedSolomon(); _rs.runReedSolomon(); Console.WriteLine("Hello World!"); }
public Ukcp connect(IChannel localChannel, EndPoint remoteAddress, ChannelConfig channelConfig, KcpListener kcpListener) { KcpOutput kcpOutput = new KcpOutPutImp(); ReedSolomon reedSolomon = null; if (channelConfig.FecDataShardCount != 0 && channelConfig.FecParityShardCount != 0) { reedSolomon = ReedSolomon.create(channelConfig.FecDataShardCount, channelConfig.FecParityShardCount); } var _messageExecutor = _executorPool.GetAutoMessageExecutor(); var ukcp = new Ukcp(kcpOutput, kcpListener, _messageExecutor, reedSolomon, channelConfig); var user = new User(localChannel, remoteAddress, localChannel.LocalAddress); ukcp.user(user); _channelManager.New(localChannel.LocalAddress, ukcp, null); _messageExecutor.execute(new ConnectTask(ukcp, kcpListener)); var scheduleTask = new ScheduleTask(_channelManager, ukcp, _scheduleThread); _scheduleThread.schedule(scheduleTask, TimeSpan.FromMilliseconds(ukcp.getInterval())); return(ukcp); }
public void TestAccountIdFromAddress() { var address = _account.Address.Replace(Constants.AddressPrefix, ""); var id = ReedSolomon.Decode(address); Assert.AreEqual(id, _account.Id); var addr1 = ReedSolomon.Encode(id); Assert.AreEqual(address, addr1); }
private void Generate(byte[] text, int textOffset, int textSize) { int e, k, full; DmParams dm, last; byte[] data = new byte[2500]; e = -1; if (height == 0 || width == 0) { last = dmSizes[dmSizes.Length - 1]; e = GetEncodation(text, textOffset, textSize, data, 0, last.dataSize, false); if (e < 0) { throw new Exception("The text is too big."); } for (k = 0; k < dmSizes.Length; ++k) { if (dmSizes[k].dataSize >= e) { break; } } dm = dmSizes[k]; height = dm.height; width = dm.width; } else { for (k = 0; k < dmSizes.Length; ++k) { if (height == dmSizes[k].height && width == dmSizes[k].width) { break; } } if (k == dmSizes.Length) { throw new Exception("Invalid symbol size."); } dm = dmSizes[k]; e = GetEncodation(text, textOffset, textSize, data, 0, dm.dataSize, true); if (e < 0) { throw new Exception("The text is too big."); } } image = new byte[((dm.width + 7) / 8) * dm.height]; MakePadding(data, e, dm.dataSize - e); place = Placement.DoPlacement(dm.height - (dm.height / dm.heightSection * 2), dm.width - (dm.width / dm.widthSection * 2)); full = dm.dataSize + ((dm.dataSize + 2) / dm.dataBlock) * dm.errorBlock; ReedSolomon.GenerateECC(data, dm.dataSize, dm.dataBlock, dm.errorBlock); Draw(data, full, dm); }
static void Main(string[] args) { ReedSolomon _rs = new ReedSolomon(); //initialize parity bytes int encodelength = 1472; //Byteencodelength int dataleng = _rs.GetDataLeng(encodelength); int[] dataInt = new int[dataleng / 4]; //initialize for (int i = 0; i < dataInt.Length; i++) { dataInt[i] = i; } byte[] data = new byte[dataInt.Length * sizeof(int)]; Buffer.BlockCopy(dataInt, 0, data, 0, data.Length); byte[] encode = new byte[encodelength]; //_rs.encode(data, encode); ////add error //Random _random = new Random(); //for(int i = 0; i < 29; i++) { // encode[_random.Next(encode.Length - 1)] ^= (byte)_random.Next(); //} ////decode //byte[] decodedata = new byte[data.Length]; //int errorDecode = _rs.decode(encode, decodedata); ////check correct decode //for(int i = 0; i < dataleng; i++) { // if(data[i] != decodedata[i]) { // Console.WriteLine("error"); // break; // } //} clientList = new List <client_IPEndPoint>() { new client_IPEndPoint() { ID_client = "20154023", On = true, NumSend = 1 }, new client_IPEndPoint() { ID_client = "00000001", On = true } }; UDPsocket udpsocket = new UDPsocket(clientList, encode, data); udpsocket.UDPsocketSend(); //Console.WriteLine("Hello World!"); }
public void ProperlyCorrects2ErrorsInAMessageLoop() { var random = new Random(1); for (var j = 0; j < 5;) { var reedSolomon = new ReedSolomon(); var data = new int[223]; for (var i = 0; i < 223; i++) { data[i] = random.Next(1, 255); } var modifiedData = reedSolomon.EncodeRawBytesArray(data); var modifIndex = random.Next(255); var modifValue = random.Next(255); while (modifValue == modifiedData[modifIndex]) { modifValue = random.Next(255); } modifiedData[modifIndex] = modifValue; var modifIndex2 = random.Next(255); var modifValue2 = random.Next(255); while (modifIndex == modifIndex2) { modifIndex2 = random.Next(255); } while (modifValue2 == modifiedData[modifIndex2]) { modifValue2 = random.Next(255); } modifiedData[modifIndex2] = modifValue2; var simpleDecoder = new SimpleRSDecoder(GenericGF.DATA_MATRIX_FIELD_256); var response = simpleDecoder.Decode(modifiedData, 32); var bytesDiffCount = GetDiffTable(data, modifiedData, 223); Assert.IsTrue(bytesDiffCount.Count <= 2); if (response) { j++; for (var i = 0; i < 223; i++) { Assert.AreEqual(data[i], modifiedData[i]); } } } }
/// <summary> /// Converts a given address to id /// </summary> /// <param name="address">Address to convert</param> /// <returns></returns> public static ulong GetId(string address) { if (!string.IsNullOrWhiteSpace(address)) { if (address.StartsWith(Constants.AddressPrefix)) { address = address.Replace(Constants.AddressPrefix, ""); } var id = ReedSolomon.Decode(address); return(id); } return(0); }
public override void ChannelRead(IChannelHandlerContext context, object message) { var msg = (DatagramPacket)message; var channel = context.Channel; var ukcp = _channelManager.get(msg); var content = msg.Content; User user; if (ukcp != null) { user = ukcp.user(); //每次收到消息重绑定地址 user.RemoteAddress = msg.Sender; ukcp.read(content); return; } //如果是新连接第一个包的sn必须为0 var sn = getSn(content, _channelConfig); if (sn != 0) { msg.Release(); return; } var messageExecutor = _executorPool.GetAutoMessageExecutor(); KcpOutput kcpOutput = new KcpOutPutImp(); ReedSolomon reedSolomon = null; if (_channelConfig.FecDataShardCount != 0 && _channelConfig.FecParityShardCount != 0) { reedSolomon = ReedSolomon.create(_channelConfig.FecDataShardCount, _channelConfig.FecParityShardCount); } ukcp = new Ukcp(kcpOutput, _kcpListener, messageExecutor, reedSolomon, _channelConfig); user = new User(channel, msg.Sender, msg.Recipient); ukcp.user(user); _channelManager.New(msg.Sender, ukcp, msg); messageExecutor.execute(new ConnectTask(ukcp, _kcpListener)); ukcp.read(content); var scheduleTask = new ScheduleTask(_channelManager, ukcp, _scheduleThread); _scheduleThread.schedule(scheduleTask, TimeSpan.FromMilliseconds(ukcp.getInterval())); }
private System.Drawing.Bitmap Draw() { DataMatrixDefinition def = ComputeSize(); ReedSolomon rs = new ReedSolomon(new DataMatrixInitialiser(def)); _Data = rs.Encode(_Data, 1); int row = 0, col = 4; bool up = true; foreach (byte item in _Data) { Rectangle[] r = DrawCodeword(item); if (row < _Size.Height & col < _Size.Width) { Transform(r, row, col); } if (up) { row -= 2; col += 2; up = row >= 0 && col < _Size.Width; if (!up) { row += 3; col += 1; } } else { row += 2; col -= 2; up = row >= _Size.Height && col < 0; if (up) { row += 3; col += 1; } } } throw new NotImplementedException(); }
public FecEncode(int headerOffset, ReedSolomon codec, int mtu) { this.dataShards = codec.getDataShardCount(); this.parityShards = codec.getParityShardCount(); this.shardSize = this.dataShards + this.parityShards; //this.paws = (Integer.MAX_VALUE/shardSize - 1) * shardSize; this.paws = 0xffffffffL / shardSize * shardSize; this.headerOffset = headerOffset; this.payloadOffset = headerOffset + Fec.fecHeaderSize; this.codec = codec; this.shardCache = new IByteBuffer[shardSize]; this.encodeCache = new IByteBuffer[parityShards]; zeros = PooledByteBufferAllocator.Default.DirectBuffer(mtu); zeros.WriteBytes(new byte[mtu]); }
public override void ChannelRead(IChannelHandlerContext context, object message) { long last_ts = DateTime.Now.Ticks; var msg = (DatagramPacket)message; var channel = context.Channel; var ukcp = _channelManager.get(msg); var content = msg.Content; User user; if (ukcp != null) { user = ukcp.user(); //每次收到消息重绑定地址 user.RemoteAddress = msg.Sender; ukcp.read(content); //Console.WriteLine(string.Format("(LAGS1){0}", (DateTime.Now.Ticks - last_ts)/10000.0)); return; } var messageExecutor = _executorPool.GetAutoMessageExecutor(); KcpOutput kcpOutput = new KcpOutPutImp(); ReedSolomon reedSolomon = null; if (_channelConfig.FecDataShardCount != 0 && _channelConfig.FecParityShardCount != 0) { reedSolomon = ReedSolomon.create(_channelConfig.FecDataShardCount, _channelConfig.FecParityShardCount); } ukcp = new Ukcp(kcpOutput, _kcpListener, messageExecutor, reedSolomon, _channelConfig); user = new User(channel, msg.Sender, msg.Recipient); ukcp.user(user); _channelManager.New(msg.Sender, ukcp, msg); ukcp.connect(); ukcp.read(content); var scheduleTask = new ScheduleTask(_channelManager, ukcp); //Console.WriteLine(ukcp.getInterval()); KcpUntils.scheduleHashedWheel(scheduleTask, TimeSpan.FromMilliseconds(ukcp.getInterval())); Console.WriteLine(string.Format("(LAGS2){0}", (DateTime.Now.Ticks - last_ts) / 10000.0)); }
private static void PrimaryDataCheck(int[] maxiCodewords) { // Handles error correction of primary barcodeMessage. int dataLength = 10; int eccLength = 10; byte[] data = new byte[dataLength]; byte[] result = new byte[eccLength]; for (int j = 0; j < dataLength; j++) data[j] = (byte)maxiCodewords[j]; ReedSolomon.RSInitialise(0x43, eccLength, 1); ReedSolomon.RSEncode(dataLength, data, result); for (int j = 0; j < eccLength; j++) maxiCodewords[dataLength + j] = result[eccLength - 1 - j]; }
public void ProperlyCorrectsUpto16ErrorsInAMessageLoop() { var random = new Random(1); for (var j = 0; j < 17; j++) { var reedSolomon = new ReedSolomon(); var data = new int[223]; for (var i = 0; i < 223; i++) { data[i] = random.Next(255); } var modifiedData = reedSolomon.EncodeRawBytesArray(data); var errorCount = 0; var startIndex = random.Next(0, 255 - 16); for (var k = startIndex; k < startIndex + j; k++) { var modifValue = random.Next(255); while (modifValue == modifiedData[k]) { modifValue = random.Next(255); } modifiedData[k] = modifValue; errorCount++; } var simpleDecoder = new SimpleRSDecoder(GenericGF.DATA_MATRIX_FIELD_256); var response = simpleDecoder.Decode(modifiedData, 32); var bytesDiffCount = GetDiffTable(data, modifiedData, 223); Assert.IsTrue(bytesDiffCount.Count <= errorCount); for (var i = 0; i < 223; i++) { Assert.AreEqual(data[i], modifiedData[i]); } } }
/** * Creates a new instance. * * @param output output for kcp */ public Ukcp(KcpOutput output, KcpListener kcpListener, IMessageExecutor iMessageExecutor, ReedSolomon reedSolomon, ChannelConfig channelConfig) { this._channelConfig = channelConfig; this.kcp = new Kcp(channelConfig.Conv, output); this.active = true; this._kcpListener = kcpListener; this._iMessageExecutor = iMessageExecutor; //默认2<<11 可以修改 _writeQueue = new MpscArrayQueue <IByteBuffer>(2 << 10); _readQueue = new MpscArrayQueue <IByteBuffer>(2 << 10); //recieveList = new SpscLinkedQueue<>(); int headerSize = 0; if (channelConfig.KcpTag) { headerSize += KCP_TAG; } //init crc32 if (channelConfig.Crc32Check) { var kcpOutput = kcp.Output; kcpOutput = new Crc32OutPut(kcpOutput, headerSize); kcp.Output = kcpOutput; headerSize += HEADER_CRC; } //init fec if (reedSolomon != null) { var kcpOutput = kcp.Output; _fecEncode = new FecEncode(headerSize, reedSolomon, channelConfig.Mtu); _fecDecode = new FecDecode(3 * reedSolomon.getTotalShardCount(), reedSolomon, channelConfig.Mtu); kcpOutput = new FecOutPut(kcpOutput, _fecEncode); kcp.Output = kcpOutput; headerSize += Fec.fecHeaderSizePlus2; } kcp.setReserved(headerSize); intKcpConfig(channelConfig); }
public void ProperlyNotCorrectsErrorInAMessage5() { var reedSolomon = new ReedSolomon(); var data = new int[223]; for (var i = 0; i < 223; i++) { data[i] = ((i + 50) % 255) + 1; } var modifiedData = reedSolomon.EncodeRawBytesArray(data); modifiedData[0] = 0; modifiedData[170] = 170; var simpleDecoder = new SimpleRSDecoder(GenericGF.DATA_MATRIX_FIELD_256); var response = simpleDecoder.Decode(modifiedData, 32); Assert.IsFalse(response); }
public void ProperlyDecodesNoErrorMessage() { var reedSolomon = new ReedSolomon(32); var data = new int[223]; for (var i = 0; i < 223; i++) { data[i] = i + 10; } var modifiedData = reedSolomon.EncodeRawBytesArray(data); var simpleDecoder = new SimpleRSDecoder(); var response = simpleDecoder.Decode(modifiedData, 32); Assert.IsTrue(response); for (var i = 0; i < 223; i++) { Assert.AreEqual(data[i], modifiedData[i]); } }
public void ProperlyFindsErrorInAMessage() { var reedSolomon = new ReedSolomon(32); var data = new int[223]; for (var i = 0; i < 223; i++) { data[i] = i + 10; } var modifiedData = reedSolomon.EncodeRawBytesArray(data); for (var i = 10; i < 30; i++) { modifiedData[i] = i + 5; } var simpleDecoder = new SimpleRSDecoder(); var response = simpleDecoder.Decode(modifiedData, 32); Assert.IsFalse(response); }
public void ImageDecodingTest() { Bitmap originalImage; var fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "/sandwich.bmp", FileMode.Open, FileAccess.Read); using (fileStream) { originalImage = new Bitmap(fileStream); } fileStream.Close(); var reedSolomon = new ReedSolomon(32); var data = ImageProcessing.GetRawBytesFromRGBImage(originalImage); var originalData = new int[data.Length]; Array.Copy(data, originalData, data.Length); var modifiedData = reedSolomon.EncodeRawBytesArray(data); var errorsCount = ErrorProvider.FillInPercentageOfErrors(modifiedData, 1); reedSolomon.SimplyDecodeRawBytesArray(modifiedData, data); var processedImage = ImageProcessing.GetRGBImageFromRawBytes(originalImage, data); var diffCount = 0; Bitmap diffImage; diffCount = ImageProcessing.Compare(processedImage, originalImage, out diffImage); var bytesDiffCount = GetDiffTable(originalData, data); Assert.IsTrue(bytesDiffCount.Count <= errorsCount); Assert.IsTrue(diffCount <= errorsCount); }
private System.Drawing.Bitmap Draw() { DataMatrixDefinition def = ComputeSize(); ReedSolomon rs = new ReedSolomon(new DataMatrixInitialiser(def)); _Data = rs.Encode(_Data, 1); int row = 0, col = 4; bool up = true; foreach (byte item in _Data) { Rectangle[] r = DrawCodeword(item); if (row < _Size.Height & col < _Size.Width) Transform(r, row, col); if (up) { row -= 2; col += 2; up = row >= 0 && col < _Size.Width; if (!up) { row += 3; col += 1; } } else { row += 2; col -= 2; up = row >= _Size.Height && col < 0; if (up) { row += 3; col += 1; } } } throw new NotImplementedException(); }
private void ProcessImageTransmissionSimulation(Params parms, int iterator, int fileOrder) { var errorMeasureValue = parms.ErrorMeasureValue; var correctionBytesCount = parms.CorrectionBytesCount; var decoderType = parms.RsDecoderType; var errorProviderType = parms.RsErrorProviderType; var orderNo = parms.OrderNo; const int blockSize = 255; var tries = 0; object clonedImage = null; while (clonedImage == null && tries < 5) { try { clonedImage = iterator % 2 == 0 ? _originalImage0.Clone() : _originalImage1.Clone(); } catch (InvalidOperationException ioe) { tries++; } } if (tries >= 5) { return; } var image = (Bitmap)clonedImage; var stopwatch = new Stopwatch(); var reedSolomon = new ReedSolomon(correctionBytesCount); var data = ImageProcessing.GetRawBytesFromRGBImage(image); stopwatch.Reset(); stopwatch.Start(); var modifiedData = reedSolomon.EncodeRawBytesArray(data); stopwatch.Stop(); var errorsCount = 0; switch (errorProviderType) { case ErrorProviderType.ErrorsTotalCount: errorsCount = ErrorProvider.FillInErrors(modifiedData, errorMeasureValue); break; case ErrorProviderType.PercentageOfErrors: errorsCount = ErrorProvider.FillInPercentageOfErrors(modifiedData, errorMeasureValue); break; case ErrorProviderType.SingleErrorsForEveryBlock: errorsCount = ErrorProvider.FillInErrorsForEveryBlock(modifiedData, errorMeasureValue, blockSize); break; case ErrorProviderType.ErrorsWithProbability: errorsCount = ErrorProvider.FillInErrorsWithProbability(modifiedData, (double)errorMeasureValue / 100); break; case ErrorProviderType.GroupErrorsForEveryBlock: errorsCount = ErrorProvider.FillInGroupErrorsForEveryBlock(modifiedData, errorMeasureValue, blockSize); break; } stopwatch.Start(); if (decoderType.Equals(DecoderType.Extended)) { reedSolomon.DecodeRawBytesArray(modifiedData, data); } else { reedSolomon.SimplyDecodeRawBytesArray(modifiedData, data); } stopwatch.Stop(); var processedImage = ImageProcessing.GetRGBImageFromRawBytes(image, data); var diffCount = 0; try { Bitmap diffImage; diffCount = ImageProcessing.Compare(processedImage, image, out diffImage); } catch (InvalidOperationException ioe) { var singleResultException = new List <int> { errorMeasureValue, (int)errorProviderType, correctionBytesCount, (int)decoderType, 0, 0, 0, orderNo, fileOrder }; _results.TryAdd(singleResultException); return; } var singleResult = new List <int> { errorMeasureValue, (int)errorProviderType, correctionBytesCount, (int)decoderType, errorsCount, (int)stopwatch.ElapsedMilliseconds, diffCount, orderNo, fileOrder }; _results.TryAdd(singleResult); }
internal virtual int[] correctDataBlocks(int[] blocks) { int num1 = 0; int dataCapacity = this.qrCodeSymbol.DataCapacity; int[] numArray1 = new int[dataCapacity]; int errorCollectionCode = this.qrCodeSymbol.NumErrorCollectionCode; int numRsBlocks = this.qrCodeSymbol.NumRSBlocks; int NPAR = errorCollectionCode / numRsBlocks; if (numRsBlocks == 1) { ReedSolomon reedSolomon = new ReedSolomon(blocks, NPAR); reedSolomon.correct(); int num2 = num1 + reedSolomon.NumCorrectedErrors; if (num2 > 0) { QRCodeDecoder.canvas.println(Convert.ToString(num2) + " data errors corrected."); } else { QRCodeDecoder.canvas.println("No errors found."); } this.numLastCorrections = num2; this.correctionSucceeded = reedSolomon.CorrectionSucceeded; return(blocks); } int length1 = dataCapacity % numRsBlocks; if (length1 == 0) { int length2 = dataCapacity / numRsBlocks; int[][] numArray2 = new int[numRsBlocks][]; for (int index = 0; index < numRsBlocks; ++index) { numArray2[index] = new int[length2]; } int[][] numArray3 = numArray2; for (int index1 = 0; index1 < numRsBlocks; ++index1) { for (int index2 = 0; index2 < length2; ++index2) { numArray3[index1][index2] = blocks[index2 * numRsBlocks + index1]; } ReedSolomon reedSolomon = new ReedSolomon(numArray3[index1], NPAR); reedSolomon.correct(); num1 += reedSolomon.NumCorrectedErrors; this.correctionSucceeded = reedSolomon.CorrectionSucceeded; } int num2 = 0; for (int index1 = 0; index1 < numRsBlocks; ++index1) { for (int index2 = 0; index2 < length2 - NPAR; ++index2) { numArray1[num2++] = numArray3[index1][index2]; } } } else { int length2 = dataCapacity / numRsBlocks; int length3 = dataCapacity / numRsBlocks + 1; int length4 = numRsBlocks - length1; int[][] numArray2 = new int[length4][]; for (int index = 0; index < length4; ++index) { numArray2[index] = new int[length2]; } int[][] numArray3 = numArray2; int[][] numArray4 = new int[length1][]; for (int index = 0; index < length1; ++index) { numArray4[index] = new int[length3]; } int[][] numArray5 = numArray4; for (int index1 = 0; index1 < numRsBlocks; ++index1) { if (index1 < length4) { int num2 = 0; for (int index2 = 0; index2 < length2; ++index2) { if (index2 == length2 - NPAR) { num2 = length1; } numArray3[index1][index2] = blocks[index2 * numRsBlocks + index1 + num2]; } ReedSolomon reedSolomon = new ReedSolomon(numArray3[index1], NPAR); reedSolomon.correct(); num1 += reedSolomon.NumCorrectedErrors; this.correctionSucceeded = reedSolomon.CorrectionSucceeded; } else { int num2 = 0; for (int index2 = 0; index2 < length3; ++index2) { if (index2 == length2 - NPAR) { num2 = length4; } numArray5[index1 - length4][index2] = blocks[index2 * numRsBlocks + index1 - num2]; } ReedSolomon reedSolomon = new ReedSolomon(numArray5[index1 - length4], NPAR); reedSolomon.correct(); num1 += reedSolomon.NumCorrectedErrors; this.correctionSucceeded = reedSolomon.CorrectionSucceeded; } } int num3 = 0; for (int index1 = 0; index1 < numRsBlocks; ++index1) { if (index1 < length4) { for (int index2 = 0; index2 < length2 - NPAR; ++index2) { numArray1[num3++] = numArray3[index1][index2]; } } else { for (int index2 = 0; index2 < length3 - NPAR; ++index2) { numArray1[num3++] = numArray5[index1 - length4][index2]; } } } } if (num1 > 0) { QRCodeDecoder.canvas.println(Convert.ToString(num1) + " data errors corrected."); } else { QRCodeDecoder.canvas.println("No errors found."); } this.numLastCorrections = num1; return(numArray1); }
internal void Run() { Console.WriteLine("preparing..."); BufferSet[] bufferSets = new BufferSet [NUMBER_OF_BUFFER_SETS]; for (int iBufferSet = 0; iBufferSet < NUMBER_OF_BUFFER_SETS; iBufferSet++) { bufferSets[iBufferSet] = new BufferSet(); } byte[] tempBuffer = new byte [BUFFER_SIZE]; List <string> summaryLines = new List <string>(); var csv = new StringBuilder(); csv.Append("Outer,Middle,Inner,Multiply,Encode,Check\n"); foreach (ICodingLoop codingLoop in CodingLoopBase.ALL_CODING_LOOPS) { var encodeAverage = new Measurement(); { string testName = codingLoop.GetType().Name + " encodeParity"; Console.WriteLine("\nTEST: " + testName); var codec = new ReedSolomon(DATA_COUNT, PARITY_COUNT, codingLoop); Console.WriteLine(" warm up..."); DoOneEncodeMeasurement(codec, bufferSets); DoOneEncodeMeasurement(codec, bufferSets); Console.WriteLine(" testing..."); for (int iMeasurement = 0; iMeasurement < 10; iMeasurement++) { encodeAverage.Add(DoOneEncodeMeasurement(codec, bufferSets)); } Console.WriteLine("\nAVERAGE: {0}", encodeAverage); summaryLines.Add($" {testName,-45} {encodeAverage}"); } // The encoding test should have filled all of the buffers with // correct parity, so we can benchmark parity checking. var checkAverage = new Measurement(); { string testName = codingLoop.GetType().Name + " isParityCorrect"; Console.WriteLine("\nTEST: " + testName); var codec = new ReedSolomon(DATA_COUNT, PARITY_COUNT, codingLoop); Console.WriteLine(" warm up..."); DoOneEncodeMeasurement(codec, bufferSets); DoOneEncodeMeasurement(codec, bufferSets); Console.WriteLine(" testing..."); for (int iMeasurement = 0; iMeasurement < 10; iMeasurement++) { checkAverage.Add(DoOneCheckMeasurement(codec, bufferSets, tempBuffer)); } Console.WriteLine("\nAVERAGE: {0}", checkAverage); summaryLines.Add($" {testName,-45} {checkAverage}"); } csv.Append(CodingLoopNameToCsvPrefix(codingLoop.GetType().Name)); csv.Append(encodeAverage.GetRate()); csv.Append(","); csv.Append(checkAverage.GetRate()); csv.Append("\n"); } Console.WriteLine("\n"); Console.WriteLine(csv.ToString()); Console.WriteLine("\nSummary:\n"); foreach (string line in summaryLines) { Console.WriteLine(line); } }
public void T01_ReedSolomon() { byte[] orig = Encoding.UTF8.GetBytes("Hello, world! Velit omnis consequatur nobis. Cum omnis ipsam rerum ut velit minus. Bye!"); ReedSolomon rs = new ReedSolomon(8); // first test the basics byte[] encoded = rs.Encode(orig); TestHelpers.AssertArrayEquals(encoded.Skip(rs.EccLength).ToArray(), orig); // test that the encoded data ends with the original data Assert.IsTrue(rs.Check(encoded)); TestHelpers.AssertArrayEquals(rs.Decode(encoded), orig); // we should be able to correct up to four errors in the encoded data encoded[7] = 77; encoded[22] = 44; encoded[62] = 11; encoded[81] = 0; Assert.IsFalse(rs.Check(encoded)); TestHelpers.AssertArrayEquals(rs.Decode(encoded), orig); // but not five encoded[2] = 1; Assert.IsNull(rs.Decode(encoded)); // however, if we specify the positions, we should be able to fix more TestHelpers.AssertArrayEquals(rs.Decode(encoded, new[] { 2, 7, 22, 62, 81 }, true), orig); encoded[12] = 2; TestHelpers.AssertArrayEquals(rs.Decode(encoded, new[] { 2, 7, 12, 22, 62 }, false), orig); // in fact should be able to fix at least eight errors encoded[23] = 3; encoded[40] = 4; TestHelpers.AssertArrayEquals(rs.Decode(encoded, new[] { 2, 7, 12, 22, 23, 40, 62, 81 }, true), orig); TestHelpers.AssertArrayEquals(rs.Decode(encoded, new[] { 2, 7, 12, 22, 23, 40, 62, 81 }, false), orig); // but not nine errors encoded[70] = 5; Assert.IsNull(rs.Decode(encoded, new[] { 2, 7, 12, 22, 23, 40, 62, 70, 81 }, true)); // now try the methods that take array indexes byte[] orig2 = new byte[orig.Length / 2]; int encodedLength = orig2.Length + rs.EccLength; Array.Copy(orig, orig2, orig2.Length); rs.Encode(orig, 0, orig.Length / 2, encoded, 10); // first, try the basic decoding Assert.IsTrue(rs.Check(encoded, 10, orig2.Length + rs.EccLength)); TestHelpers.AssertArrayEquals(rs.Decode(encoded, 10, encodedLength), orig2); byte[] decoded = new byte[orig2.Length + 30]; Assert.AreEqual(orig2.Length, rs.Decode(encoded, 10, encodedLength, decoded, 20)); TestHelpers.AssertArrayEquals(decoded.Skip(20).Take(orig2.Length).ToArray(), orig2); // now fix four errors with positions unspecified encoded[11] = 77; encoded[17] = 44; encoded[23] = 11; encoded[34] = 0; Assert.AreEqual(orig2.Length, rs.Decode(encoded, 10, encodedLength, decoded, 20)); TestHelpers.AssertArrayEquals(decoded.Skip(20).Take(orig2.Length).ToArray(), orig2); // now fix eight errors with positions specified encoded[13] = 1; encoded[19] = 2; encoded[27] = 3; encoded[31] = 4; Assert.AreEqual(-1, rs.Decode(encoded, 10, encodedLength, decoded, 20)); // check that it gives a failure result without positions Assert.AreEqual(orig2.Length, rs.Decode(encoded, 10, encodedLength, decoded, 20, new[] { 1, 3, 7, 9, 13, 17, 21, 24 })); TestHelpers.AssertArrayEquals(decoded.Skip(20).Take(orig2.Length).ToArray(), orig2); }
internal virtual int[] correctDataBlocks(int[] blocks) { int num = 0; int dataCapacity = qrCodeSymbol.DataCapacity; int[] array = new int[dataCapacity]; int numErrorCollectionCode = qrCodeSymbol.NumErrorCollectionCode; int numRSBlocks = qrCodeSymbol.NumRSBlocks; int num2 = numErrorCollectionCode / numRSBlocks; if (numRSBlocks == 1) { ReedSolomon reedSolomon = new ReedSolomon(blocks, num2); reedSolomon.correct(); num += reedSolomon.NumCorrectedErrors; if (num > 0) { canvas.println(Convert.ToString(num) + " data errors corrected."); } else { canvas.println("No errors found."); } numLastCorrections = num; correctionSucceeded = reedSolomon.CorrectionSucceeded; return(blocks); } int num3 = dataCapacity % numRSBlocks; if (num3 == 0) { int num4 = dataCapacity / numRSBlocks; int[][] array2 = new int[numRSBlocks][]; for (int i = 0; i < numRSBlocks; i++) { array2[i] = new int[num4]; } int[][] array3 = array2; for (int i = 0; i < numRSBlocks; i++) { for (int j = 0; j < num4; j++) { array3[i][j] = blocks[j * numRSBlocks + i]; } ReedSolomon reedSolomon = new ReedSolomon(array3[i], num2); reedSolomon.correct(); num += reedSolomon.NumCorrectedErrors; correctionSucceeded = reedSolomon.CorrectionSucceeded; } int num5 = 0; for (int i = 0; i < numRSBlocks; i++) { for (int j = 0; j < num4 - num2; j++) { array[num5++] = array3[i][j]; } } } else { int num6 = dataCapacity / numRSBlocks; int num7 = dataCapacity / numRSBlocks + 1; int num8 = numRSBlocks - num3; int[][] array4 = new int[num8][]; for (int k = 0; k < num8; k++) { array4[k] = new int[num6]; } int[][] array5 = array4; int[][] array6 = new int[num3][]; for (int l = 0; l < num3; l++) { array6[l] = new int[num7]; } int[][] array7 = array6; for (int i = 0; i < numRSBlocks; i++) { int num9; ReedSolomon reedSolomon; if (i < num8) { num9 = 0; for (int j = 0; j < num6; j++) { if (j == num6 - num2) { num9 = num3; } array5[i][j] = blocks[j * numRSBlocks + i + num9]; } reedSolomon = new ReedSolomon(array5[i], num2); reedSolomon.correct(); num += reedSolomon.NumCorrectedErrors; correctionSucceeded = reedSolomon.CorrectionSucceeded; continue; } num9 = 0; for (int j = 0; j < num7; j++) { if (j == num6 - num2) { num9 = num8; } array7[i - num8][j] = blocks[j * numRSBlocks + i - num9]; } reedSolomon = new ReedSolomon(array7[i - num8], num2); reedSolomon.correct(); num += reedSolomon.NumCorrectedErrors; correctionSucceeded = reedSolomon.CorrectionSucceeded; } int num5 = 0; for (int i = 0; i < numRSBlocks; i++) { if (i < num8) { for (int j = 0; j < num6 - num2; j++) { array[num5++] = array5[i][j]; } } else { for (int j = 0; j < num7 - num2; j++) { array[num5++] = array7[i - num8][j]; } } } } if (num > 0) { canvas.println(Convert.ToString(num) + " data errors corrected."); } else { canvas.println("No errors found."); } numLastCorrections = num; return(array); }
internal virtual int[] correctDataBlocks(int[] blocks) { ReedSolomon solomon; int num8; int num9; int num10; int num = 0; int dataCapacity = this.qrCodeSymbol.DataCapacity; int[] numArray = new int[dataCapacity]; int numErrorCollectionCode = this.qrCodeSymbol.NumErrorCollectionCode; int numRSBlocks = this.qrCodeSymbol.NumRSBlocks; int nPAR = numErrorCollectionCode / numRSBlocks; if (numRSBlocks == 1) { solomon = new ReedSolomon(blocks, nPAR); solomon.correct(); num += solomon.NumCorrectedErrors; if (num > 0) { canvas.println(Convert.ToString(num) + " data errors corrected."); } else { canvas.println("No errors found."); } this.numLastCorrections = num; this.correctionSucceeded = solomon.CorrectionSucceeded; return(blocks); } int num6 = dataCapacity % numRSBlocks; if (num6 == 0) { int num7 = dataCapacity / numRSBlocks; int[][] numArray2 = new int[numRSBlocks][]; for (num8 = 0; num8 < numRSBlocks; num8++) { numArray2[num8] = new int[num7]; } int[][] numArray3 = numArray2; for (num8 = 0; num8 < numRSBlocks; num8++) { num9 = 0; while (num9 < num7) { numArray3[num8][num9] = blocks[(num9 * numRSBlocks) + num8]; num9++; } solomon = new ReedSolomon(numArray3[num8], nPAR); solomon.correct(); num += solomon.NumCorrectedErrors; this.correctionSucceeded = solomon.CorrectionSucceeded; } num10 = 0; for (num8 = 0; num8 < numRSBlocks; num8++) { num9 = 0; while (num9 < (num7 - nPAR)) { numArray[num10++] = numArray3[num8][num9]; num9++; } } } else { int num11 = dataCapacity / numRSBlocks; int num12 = (dataCapacity / numRSBlocks) + 1; int num13 = numRSBlocks - num6; int[][] numArray4 = new int[num13][]; for (int i = 0; i < num13; i++) { numArray4[i] = new int[num11]; } int[][] numArray5 = numArray4; int[][] numArray6 = new int[num6][]; for (int j = 0; j < num6; j++) { numArray6[j] = new int[num12]; } int[][] numArray7 = numArray6; for (num8 = 0; num8 < numRSBlocks; num8++) { int num16; if (num8 < num13) { num16 = 0; num9 = 0; while (num9 < num11) { if (num9 == (num11 - nPAR)) { num16 = num6; } numArray5[num8][num9] = blocks[((num9 * numRSBlocks) + num8) + num16]; num9++; } solomon = new ReedSolomon(numArray5[num8], nPAR); solomon.correct(); num += solomon.NumCorrectedErrors; this.correctionSucceeded = solomon.CorrectionSucceeded; } else { num16 = 0; num9 = 0; while (num9 < num12) { if (num9 == (num11 - nPAR)) { num16 = num13; } numArray7[num8 - num13][num9] = blocks[((num9 * numRSBlocks) + num8) - num16]; num9++; } solomon = new ReedSolomon(numArray7[num8 - num13], nPAR); solomon.correct(); num += solomon.NumCorrectedErrors; this.correctionSucceeded = solomon.CorrectionSucceeded; } } num10 = 0; for (num8 = 0; num8 < numRSBlocks; num8++) { if (num8 < num13) { num9 = 0; while (num9 < (num11 - nPAR)) { numArray[num10++] = numArray5[num8][num9]; num9++; } } else { for (num9 = 0; num9 < (num12 - nPAR); num9++) { numArray[num10++] = numArray7[num8 - num13][num9]; } } } } if (num > 0) { canvas.println(Convert.ToString(num) + " data errors corrected."); } else { canvas.println("No errors found."); } this.numLastCorrections = num; return(numArray); }
/// <summary>Creates a barcode.</summary> /// <param name="text">the text</param> /// <param name="textOffset">the offset to the start of the text</param> /// <param name="textSize">the text size</param> /// <returns> /// the status of the generation. It can be one of this values: /// <p/> /// <CODE>DM_NO_ERROR</CODE> - no error.<br /> /// <CODE>DM_ERROR_TEXT_TOO_BIG</CODE> - the text is too big for the symbology capabilities.<br /> /// <CODE>DM_ERROR_INVALID_SQUARE</CODE> - the dimensions given for the symbol are illegal.<br /> /// <CODE>DM_ERROR_EXTENSION</CODE> - an error was while parsing an extension. /// </returns> public virtual int SetCode(byte[] text, int textOffset, int textSize) { int extCount; int e; int k; int full; DmParams dm; DmParams last; byte[] data = new byte[2500]; extOut = 0; extCount = ProcessExtensions(text, textOffset, textSize, data); if (extCount < 0) { return(DM_ERROR_EXTENSION); } e = -1; if (height == 0 || width == 0) { last = dmSizes[dmSizes.Length - 1]; e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, last.dataSize - extCount, options, false); if (e < 0) { return(DM_ERROR_TEXT_TOO_BIG); } e += extCount; for (k = 0; k < dmSizes.Length; ++k) { if (dmSizes[k].dataSize >= e) { break; } } dm = dmSizes[k]; height = dm.height; width = dm.width; } else { for (k = 0; k < dmSizes.Length; ++k) { if (height == dmSizes[k].height && width == dmSizes[k].width) { break; } } if (k == dmSizes.Length) { return(DM_ERROR_INVALID_SQUARE); } dm = dmSizes[k]; e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, dm.dataSize - extCount, options , true); if (e < 0) { return(DM_ERROR_TEXT_TOO_BIG); } e += extCount; } if ((options & DM_TEST) != 0) { return(DM_NO_ERROR); } image = new byte[(dm.width + 2 * ws + 7) / 8 * (dm.height + 2 * ws)]; MakePadding(data, e, dm.dataSize - e); place = Placement.DoPlacement(dm.height - dm.height / dm.heightSection * 2, dm.width - dm.width / dm.widthSection * 2); full = dm.dataSize + (dm.dataSize + 2) / dm.dataBlock * dm.errorBlock; ReedSolomon.GenerateECC(data, dm.dataSize, dm.dataBlock, dm.errorBlock); Draw(data, full, dm); return(DM_NO_ERROR); }
internal ulong GetAccountIdFromReedSolomon(string reedSolomonAddress) { return(ReedSolomon.Decode(reedSolomonAddress)); }
internal string GetReedSolomonFromAccountId(ulong accountId) { return(ReedSolomon.Encode(accountId)); }
internal virtual int[] correctDataBlocks(int[] blocks) { int numCorrections = 0; int dataCapacity = qrCodeSymbol.DataCapacity; int[] dataBlocks = new int[dataCapacity]; int numErrorCollectionCode = qrCodeSymbol.NumErrorCollectionCode; int numRSBlocks = qrCodeSymbol.NumRSBlocks; int eccPerRSBlock = numErrorCollectionCode / numRSBlocks; if (numRSBlocks == 1) { ReedSolomon corrector = new ReedSolomon(blocks, eccPerRSBlock); corrector.correct(); numCorrections += corrector.NumCorrectedErrors; if (numCorrections > 0) { canvas.println(System.Convert.ToString(numCorrections) + " data errors corrected."); } else { canvas.println("No errors found."); } numLastCorrections = numCorrections; correctionSucceeded = corrector.CorrectionSucceeded; return(blocks); } else { int numLongerRSBlocks = dataCapacity % numRSBlocks; if (numLongerRSBlocks == 0) { int lengthRSBlock = dataCapacity / numRSBlocks; int[][] tmpArray = new int[numRSBlocks][]; for (int i = 0; i < numRSBlocks; i++) { tmpArray[i] = new int[lengthRSBlock]; } int[][] RSBlocks = tmpArray; for (int i = 0; i < numRSBlocks; i++) { for (int j = 0; j < lengthRSBlock; j++) { RSBlocks[i][j] = blocks[j * numRSBlocks + i]; } ReedSolomon corrector = new ReedSolomon(RSBlocks[i], eccPerRSBlock); corrector.correct(); numCorrections += corrector.NumCorrectedErrors; correctionSucceeded = corrector.CorrectionSucceeded; } int p = 0; for (int i = 0; i < numRSBlocks; i++) { for (int j = 0; j < lengthRSBlock - eccPerRSBlock; j++) { dataBlocks[p++] = RSBlocks[i][j]; } } } else { int lengthShorterRSBlock = dataCapacity / numRSBlocks; int lengthLongerRSBlock = dataCapacity / numRSBlocks + 1; int numShorterRSBlocks = numRSBlocks - numLongerRSBlocks; int[][] tmpArray2 = new int[numShorterRSBlocks][]; for (int i2 = 0; i2 < numShorterRSBlocks; i2++) { tmpArray2[i2] = new int[lengthShorterRSBlock]; } int[][] shorterRSBlocks = tmpArray2; int[][] tmpArray3 = new int[numLongerRSBlocks][]; for (int i3 = 0; i3 < numLongerRSBlocks; i3++) { tmpArray3[i3] = new int[lengthLongerRSBlock]; } int[][] longerRSBlocks = tmpArray3; for (int i = 0; i < numRSBlocks; i++) { if (i < numShorterRSBlocks) { int mod = 0; for (int j = 0; j < lengthShorterRSBlock; j++) { if (j == lengthShorterRSBlock - eccPerRSBlock) { mod = numLongerRSBlocks; } shorterRSBlocks[i][j] = blocks[j * numRSBlocks + i + mod]; } ReedSolomon corrector = new ReedSolomon(shorterRSBlocks[i], eccPerRSBlock); corrector.correct(); numCorrections += corrector.NumCorrectedErrors; correctionSucceeded = corrector.CorrectionSucceeded; } else { int mod = 0; for (int j = 0; j < lengthLongerRSBlock; j++) { if (j == lengthShorterRSBlock - eccPerRSBlock) { mod = numShorterRSBlocks; } longerRSBlocks[i - numShorterRSBlocks][j] = blocks[j * numRSBlocks + i - mod]; } ReedSolomon corrector = new ReedSolomon(longerRSBlocks[i - numShorterRSBlocks], eccPerRSBlock); corrector.correct(); numCorrections += corrector.NumCorrectedErrors; correctionSucceeded = corrector.CorrectionSucceeded; } } int p = 0; for (int i = 0; i < numRSBlocks; i++) { if (i < numShorterRSBlocks) { for (int j = 0; j < lengthShorterRSBlock - eccPerRSBlock; j++) { dataBlocks[p++] = shorterRSBlocks[i][j]; } } else { for (int j = 0; j < lengthLongerRSBlock - eccPerRSBlock; j++) { dataBlocks[p++] = longerRSBlocks[i - numShorterRSBlocks][j]; } } } } if (numCorrections > 0) { canvas.println(Convert.ToString(numCorrections) + " data errors corrected."); } else { canvas.println("No errors found."); } numLastCorrections = numCorrections; return(dataBlocks); } }
public NodeECCDecoder(IPipe Input, IPipe Output) : base(Input, Output) { ecc = new ReedSolomon(); }