private static void RC4(ref Byte[] bytes, Byte[] key) { Byte[] s = new Byte[256]; Byte[] k = new Byte[256]; Byte temp; int i, j; for (i = 0; i < 256; i++) { s[i] = (Byte)i; k[i] = key[i % key.GetLength(0)]; } j = 0; for (i = 0; i < 256; i++) { j = (j + s[i] + k[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; } i = j = 0; for (int x = 0; x < bytes.GetLength(0); x++) { i = (i + 1) % 256; j = (j + s[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; int t = (s[i] + s[j]) % 256; bytes[x] ^= s[t]; } }
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { // シリアルポートからデータ受信 { Byte[] buff = new Byte[serialPort.BytesToRead]; serialPort.Read(buff, 0, buff.GetLength(0)); // 受信サイズの10バイトたまるまで、受け取る for (int i = 0; i < buff.Length; i++) { sirialResvPool[resvIdx + i] = buff[i]; } resvIdx += buff.Length; } // 10バイト受け取るまで待つ if (resvIdx < 10) return; resvIdx = 0; try { for (int i = 0; i < 10; i++) { resiveStr += ((int)sirialResvPool[i]).ToString() + " "; } } catch { } }
static void Main(string[] args) { string data = ""; byte[] sendBytes = new Byte[1024]; byte[] rcvPacket = new Byte[1024]; UdpClient client = new UdpClient(); IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString()); client.Connect(address, 8008); IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0); Console.WriteLine("Client is Started"); Console.WriteLine("Type your message"); while (data != "q") { data = Console.ReadLine(); sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data); client.Send(sendBytes, sendBytes.GetLength(0)); rcvPacket = client.Receive(ref remoteIPEndPoint); string rcvData = Encoding.ASCII.GetString(rcvPacket); Console.WriteLine("Handling client at " + remoteIPEndPoint + " - "); Console.WriteLine("Message Received: " + rcvPacket.ToString()); } Console.WriteLine("Close Port Command Sent"); //user feedback Console.ReadLine(); client.Close(); //close connection }
public static void RC4(ref Byte[] bytes, Byte[] key) { Byte[] result = new byte[256]; Byte[] s = new Byte[256]; Byte[] k = new Byte[256]; Byte temp; int i, j; int n = key.Length; for (i = 0; i < 256; i++) { s[i] = (Byte)i; //k[i] = key[i % key.GetLength(0)]; k[i] = key[i % n]; } j = 0; for (i = 0; i < 256; i++) { j = (j + s[i] + k[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; } i = 0; j = 0; for (int x = 0; x < bytes.GetLength(0); x++) { i = (i + 1) % 256; j = (j + s[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; int t = (s[i] + s[j]) % 256; bytes[x] ^= s[t]; //Salida en hex //Console.Write("{0:X2}", (bytes[x])); //Salida caracteres imprimibles if (string.IsNullOrEmpty(outFileName)) { if ((bytes[x] < 32) | (bytes[x] == 129) | (bytes[x] == 141) | (bytes[x] == 143) | (bytes[x] == 144) | (bytes[x] == 157) | (bytes[x] == 159)) { Console.Write("."); } else { Console.Write(Encoding.Default.GetString(bytes, x, 1)); } } } //Salida a archivo if (!string.IsNullOrEmpty(outFileName)) { File.WriteAllBytes(outFileName, bytes); } }
private static void ExecShellcode() { // Convert shellcode string to byte array Byte[] sc_bytes = new Byte[shellcode.Length]; for (int i = 0; i < shellcode.Length; i++) { sc_bytes [i] = (Byte) shellcode [i]; } // Prevent garbage collector from moving the shellcode byte array GCHandle pinnedByteArray = GCHandle.Alloc(sc_bytes, GCHandleType.Pinned); // Get handle for shellcode address and address of the page it is located in IntPtr shellcodePtr = pinnedByteArray.AddrOfPinnedObject(); IntPtr shellcodePagePtr = GetPageBaseAddress(shellcodePtr); Int32 shellcodeOffset = (Int32)shellcodePtr - (Int32)shellcodePagePtr; Int32 shellcodeLen = sc_bytes.GetLength (0); // Some debugging information Console.WriteLine ("Page Size: {0}", PAGE_SIZE.ToString ()); Console.WriteLine ("Shellcode address: 0x{0}", shellcodePtr.ToString("x")); Console.WriteLine ("First page start address: 0x{0}", shellcodePagePtr.ToString("x")); Console.WriteLine ("Shellcode offset: {0}", shellcodeOffset); Console.WriteLine ("Shellcode length: {0}", shellcodeLen); // Make shellcode memory executable MakeMemoryExecutable(shellcodePagePtr); // Check if shellcode spans across more than 1 page; make all extra pages // executable too Int32 pageCounter = 1; while (shellcodeOffset + shellcodeLen > PAGE_SIZE) { shellcodePagePtr = GetPageBaseAddress(shellcodePtr + pageCounter * PAGE_SIZE); pageCounter++; shellcodeLen -= PAGE_SIZE; MakeMemoryExecutable(shellcodePagePtr); } // Debug information Console.WriteLine ("Pages taken by the shellcode: {0}", pageCounter); // Make shellcode callable by converting pointer to delegate ShellcodeFuncPrototype shellcode_func = (ShellcodeFuncPrototype) Marshal.GetDelegateForFunctionPointer( shellcodePtr, typeof(ShellcodeFuncPrototype)); shellcode_func(); // Execute shellcode pinnedByteArray.Free(); }
public void TestData() { Byte[,] data = new Byte[20, 30]; Random r = new Random(); Byte[] bytes = new Byte[data.Length]; r.NextBytes(bytes); for (int i = 0; i < data.GetLength(0); i++) for (int j = 0; j < data.GetLength(1); j++) data[i, j] = bytes[i * data.GetLength(1) + j]; Matrix<Byte> m = new Matrix<byte>(data); Byte[,] data2 = m.Data; for (int i = 0; i < data.GetLength(0); i++) for (int j = 0; j < data.GetLength(1); j++) { Assert.AreEqual(data[i, j], data2[i, j]); Assert.AreEqual(data[i, j], m[i, j]); } }
public void DrawMaze(Byte[,] mazeToDraw) { for (UInt16 y = 0; y < mazeToDraw.GetLength(1); y++) { for (UInt16 x = 0; x < mazeToDraw.GetLength(0); x++) { // here: if cell = 255 => fill cell with a gray color // with layout ==> new type to handle ! if (mazeToDraw[x, y] == 255) { //Console.WriteLine(string.Format("[{0},{1}] = block", x,y)); drawABlockedCell(x, y); } else { foreach (Direction way in Enum.GetValues(typeof(Direction))) { drawAWall(x, y, (Direction)mazeToDraw[x, y]); } } } } }
public string receive() { if (clientSock.Available > 0) { Byte[] dat = new Byte[clientSock.Available]; try { netStream.Read(dat, 0, dat.GetLength(0)); } catch (Exception ex) { eventLog.WriteEntry("Failed to receive message" + ex.Message); } return System.Text.Encoding.GetEncoding("utf-8").GetString(dat); } return "Fail"; }
public Byte[] RC4_Process(Byte[] data, Byte[] key) { Byte[] s = new Byte[256]; Byte[] k = new Byte[256]; Byte temp; int i, j; for (i = 0; i < 256; i++) { s[i] = (Byte)i; k[i] = key[i % key.GetLength(0)]; } j = 0; for (i = 0; i < 256; i++) { j = (j + s[i] + k[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; } byte[] OUT = new byte[data.Length]; i = j = 0; unchecked { for (int x = 0; x < data.GetLength(0); x++) { i = (i + 1) % 256; j = (j + s[i]) % 256; temp = s[i]; s[i] = s[j]; s[j] = temp; int t = (s[i] + s[j]) % 256; OUT[x] = (byte)(data[x] ^ s[t]); } } return OUT; }
private string[] DecodeMessage(Byte[] bytes) { int arraySize = bytes.GetLength(0); string[] messages = new string[arraySize]; for (int i = 0; i < arraySize; i++) { switch (bytes[i]) { case (byte)Message.I2C_StartSet: messages[i] = "I2C start set"; break; case (byte)Message.I2C_Busy: messages[i] = "I2C is busy"; break; case (byte)Message.I2C_StartSucc: messages[i] = "I2C start successful"; break; case (byte)Message.I2C_NoAck: messages[i] = "I2C no ack. Stop is set"; break; case (byte)Message.I2C_Transmitter: messages[i] = "I2C transmitter"; break; case (byte)Message.I2C_Receiver: messages[i] = "I2C receiver"; break; case (byte)Message.I2C_CommandTrans: messages[i] = "I2C command transmitted"; break; case (byte)Message.I2C_ByteRec: messages[i] = "I2C byte received"; break; default: messages[i] = "Unknown command"; break; } } return messages; }
static string getBlock(IPAddress server, int port, int blockSize) { int localport = 8009; string returnData = ""; UdpClient client = new UdpClient(); UdpClient client2 = new UdpClient(localport); Byte[] sendBytes = new Byte[1024]; Byte[] receiveBytes = new Byte[1024]; try { IPEndPoint remoteIPEndPoint = new IPEndPoint(server, localport); client.Connect(server.ToString(), port); sendBytes = Encoding.ASCII.GetBytes("NEW"+blockSize.ToString()); client.Send(sendBytes, sendBytes.GetLength(0)); receiveBytes = client2.Receive(ref remoteIPEndPoint); returnData = Encoding.ASCII.GetString(receiveBytes); } catch (Exception e) { Console.WriteLine("Error with the Server Name: {0}", e.ToString()); } return returnData.TrimEnd(); }
/// <summary> /// shows display text periodically /// </summary> /// <param name="obj"></param> /// <param name="e"></param> private void tiWriteText_ElapsedHandler(Object obj, ElapsedEventArgs e) { //stop this timer tiWriteText.Enabled = false; //assign standard timer period tiWriteText.Interval = iScrollPeriodStandard; //create handle for datagram Byte[] btDatagram = new Byte[64]; //byte position in datagram for content //Byte btBytePos = new Byte(); //RAM adress for text Byte btRAMadress = new Byte(); //create 1-dimensional byte array for futaba characters to be transferred btToFutaba = null; btToFutaba = new Byte[btTextToByteArray.GetLength(0) * btTextToByteArray.GetLength(1)]; //fill the array from text-to-byte array argument //(means: convert 2-dim. array to 1-dim array) for (int s = 0; s < btTextToByteArray.GetLength(0); s++) for (int t = 0; t < btTextToByteArray.GetLength(1); t++) btToFutaba[(s * btTextToByteArray.GetLength(1)) + t] = btTextToByteArray[s, t]; // //reset RAM address to display start position btRAMadress = 0x00; //clear datagram for (int m = 0x04; m < btDatagram.GetLength(0); m++) btDatagram[m] = 0x00; // //as long as display is not completely filled while (btRAMadress < 0xC0) { //create datagram for RAM adress btDatagram[0x00] = 0x03; //count of successive bytes btDatagram[0x01] = 0x1b; //header (fix value) btDatagram[0x02] = 0x60; //command: set RAM adress btDatagram[0x03] = btRAMadress; //RAM adress //send command SendCommand(btDatagram); // //create datagram for characters btDatagram[0x00] = 0x3F; //count of successive bytes btDatagram[0x01] = 0x1b; //header (fix value) btDatagram[0x02] = 0x70; //command: write pixel btDatagram[0x03] = 0x30; //count of data bytes //fill in text data for (int n = 0x00; n < 0x30; n++) { //if end of text has not been reached if (((btRAMadress + n + iOffsVisibleText) < btToFutaba.GetLength(0)) && iOffsVisibleText != -iCharByteCount) //assign next text package to datagram btDatagram[n + 0x04] = btToFutaba[btRAMadress + n + iOffsVisibleText]; //if end of text has been reached else { //assign long period to timer so that end of text can conviniently be recognized tiWriteText.Interval = iScrollPeriodLong; //reset datagram content btDatagram[n + 0x04] = 0x00; //reset visible text offset iOffsVisibleText = -iCharByteCount; } //if this is the beginning of the text if (iOffsVisibleText == 0x00) { //assign long period to timer so that beginning of text can conviniently be recognized tiWriteText.Interval = iScrollPeriodLong; } } // //send command SendCommand(btDatagram); // //set RAM adress for next characters btRAMadress = Convert.ToByte(btRAMadress + 0x30); } //increase offset iOffsVisibleText += iCharByteCount; //start this timer again tiWriteText.Enabled = true; }
static void Main(string[] args) { //tells the system to only use available processor cycles allowing the program to run in the background System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Idle; //Greetings Screen Console.WriteLine("********************"); Console.WriteLine("* Distributed MD5 *"); Console.WriteLine("* Cracker *"); Console.WriteLine("********************"); Console.WriteLine(""); Console.WriteLine("********************"); Console.WriteLine("* Client *"); Console.WriteLine("********************"); Console.WriteLine(""); Console.WriteLine("********************"); Console.WriteLine("* 09000451 *"); Console.WriteLine("********************"); Console.WriteLine(""); Console.WriteLine("--------------------"); //connects to server Console.WriteLine("What is the IP of your server"); String ServerName = Console.ReadLine(); string hash = serverConnect(ServerName); Console.WriteLine("Received Hash! " + hash); Thread.Sleep(50); //starts a thread listening for multicast terminate instructions, this allows the program to continue functioning while keeping a constant listen for global instructions. Thread terminatorThread = new Thread(new ThreadStart(terminateThread)); terminatorThread.Start(); //creates udp clients for listening! UdpClient udpClient = new UdpClient(); //outgoing Udp UdpClient udpClient2 = new UdpClient(8010); //incoming port //section executes code while the thread is alive, this will include requesting new chunks to work through String resultYN = null; while (terminatorThread.IsAlive) { Byte[] sendBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time Byte[] recieveBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time String textinput = null; String returnData = ""; //sends an initial No to the server to request a chunk, as the server is keyed to pass out new chunks to clients that don't have an answer. try { IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered udpClient.Connect(remoteAddr.ToString(), 8009); //address of the remotelocation textinput = "n"; sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024)); udpClient.Send(sendBytes, sendBytes.GetLength(0)); //send the packet }//end of the try catch (Exception e) { Console.WriteLine("Error with the Server Name: {0}", e.ToString()); Console.WriteLine("Did you start the Server First ?"); }//end of the catch try { //the IP Address.any allows any valid matching address for this machine to be used //i.e. loopback, broadcast, IPv4, IPv6 IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 8009); //open port 8009 on this machine udpClient2.Client.ReceiveTimeout = 500; //sets timeout to prevent the programming hanging if no reply is recieved recieveBytes = udpClient2.Receive(ref remoteIPEndPoint); returnData = Encoding.ASCII.GetString(recieveBytes); } catch (Exception ex) { Console.WriteLine("Packet Timed out"); } //grabs the counter value from the returned chunk packet. it only needs one value as the clients know to increment by 100000 immediately int counter = 0; try { counter = Convert.ToInt32(returnData); } catch { counter = 0; Console.ReadLine(); Environment.Exit(0); } Console.WriteLine("Recieved Chunk {0} - {1}", counter, counter + 100000); //included to provide visual indication that the program is recieving chunks String result = checkHash(hash, counter, counter + 100000); //pass to the check hash function resultYN = result.Split()[0]; //the check hash function may pass back a yes result, this seperates the yes or no out for case checking //if the result is positive, the client sends a result packet straight away, that contains a yes terminate for the server, and the actual hash value if (resultYN == "y") { try { IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered udpClient.Connect(remoteAddr.ToString(), 8009); //address of the remotelocation //read in the text from the console textinput = result; sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024)); udpClient.Send(sendBytes, sendBytes.GetLength(0)); //send the packet }//end of the try catch (Exception e) { Console.WriteLine("Error with the Server Name: {0}", e.ToString()); Console.WriteLine("Did you start the Server First ?"); }//end of the catch } } //provides a delay to program close Console.WriteLine(""); Console.ReadLine(); }
//provides initial connection to the server, and checks for timeout, if no response is found static string serverConnect(string ServerName) { //creates updclient on this machine to recieve data UdpClient udpClient = new UdpClient(); UdpClient udpClient2 = new UdpClient(8010); Byte[] sendBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time String textinput = null; //requests input of ip of server - consider switching to a multicast to join the server group String returnData = ""; String hello = null; String hash = null; //sends data to the server address, in this case a Hello packet, if a hello is recieved back then the loop ends or until 4 packets have been sent int counter = 0; while (counter < 4) { try { IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered udpClient.Connect(remoteAddr.ToString(), 8009); //address of the remotelocation Console.WriteLine("Testing Connection"); //read in the text from the console textinput = "Hello"; sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024)); udpClient.Send(sendBytes, sendBytes.GetLength(0)); //send the packet }//end of the try catch (Exception e) { Console.WriteLine("Error with the Server Name: {0}", e.ToString()); Console.WriteLine("Did you start the Server First ?"); }//end of the catch try { Byte[] recieveBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time //the IP Address.any allows any valid matching address for this machine to be used //i.e. loopback, broadcast, IPv4, IPv6 IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 8010); //open port 8010 on this machine udpClient2.Client.ReceiveTimeout = 500; //sets timeout to prevent the programming hanging if no reply is recieved recieveBytes = udpClient2.Receive(ref remoteIPEndPoint); returnData = Encoding.ASCII.GetString(recieveBytes); hello = returnData.Split()[0]; hash = returnData.Split()[1]; } catch (Exception ex) { Console.WriteLine("Packet {0} Timed out. Sending until 4!", counter + 1); counter++; } if (counter == 4) { Console.WriteLine("Unable to establish connection: program now terminating!"); Console.WriteLine("Press enter to close"); } if (hello == "Hello") { Console.WriteLine("Connected To Server!"); Console.WriteLine(""); counter = 4; } } udpClient.Close(); udpClient2.Close(); return hash; }
/* * Function: BuileNetwork * Description:MATStrategy算法读取函数 * Parameters: * Byte[,] bytMatrix 从邻接矩阵生成cNet网络 * StyleSet pStyle 绘制样式集 * Return Value:cNet */ cNet BuileNetwork(Byte[,] bytMatrix) { cNet NewNet; IfPlatform NewNode; int intRow, intCol, i, j; intRow = bytMatrix.GetLength(0); intCol = bytMatrix.GetLength(1); NewNet = new cNet(intRow); for(i = 0; i < intRow; i++) { NewNode = new cNode(i); for(j = 0; j<intCol; j++) { if(bytMatrix[i, j] != 0) { NewNode.AddEdge(j, (double)bytMatrix[i, j]); } } NewNet.Network.Add(NewNode); } if (NewNet.intNumber == 0) { return null; } return NewNet; }
private void WriteBinaryString(Byte[] value) { Int32 length = value.GetLength(0); stream.WriteByte(PHPSerializationTag.BinaryString); stream.WriteByte(PHPSerializationTag.Colon); WriteNumber(length); stream.WriteByte(PHPSerializationTag.Colon); stream.WriteByte(PHPSerializationTag.Quote); stream.Write(value, 0, length); stream.WriteByte(PHPSerializationTag.Quote); stream.WriteByte(PHPSerializationTag.Semicolon); }
/// <summary> /// 将二值化数组转换为二值化图像 /// </summary> /// <param name="binaryArray">二值化数组</param> /// <returns>二值化图像</returns> public static Bitmap BinaryArrayToBinaryBitmap(Byte[,] binaryArray) { // 将二值化数组转换为二值化数据 Int32 PixelHeight = binaryArray.GetLength(0); Int32 PixelWidth = binaryArray.GetLength(1); Int32 Stride = ((PixelWidth + 31) >> 5) << 2; Byte[] Pixels = new Byte[PixelHeight * Stride]; for (Int32 i = 0; i < PixelHeight; i++) { Int32 Base = i * Stride; for (Int32 j = 0; j < PixelWidth; j++) { if (binaryArray[i, j] != 0) { Pixels[Base + (j >> 3)] |= Convert.ToByte(0x80 >> (j & 0x7)); } } } // 创建黑白图像 Bitmap BinaryBmp = new Bitmap(PixelWidth, PixelHeight, PixelFormat.Format1bppIndexed); // 设置调色表 ColorPalette cp = BinaryBmp.Palette; cp.Entries[0] = Color.Black; // 黑色 cp.Entries[1] = Color.White; // 白色 BinaryBmp.Palette = cp; // 设置位图图像特性 BitmapData BinaryBmpData = BinaryBmp.LockBits(new Rectangle(0, 0, PixelWidth, PixelHeight), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed); Marshal.Copy(Pixels, 0, BinaryBmpData.Scan0, Pixels.Length); BinaryBmp.UnlockBits(BinaryBmpData); return BinaryBmp; }
public static byte[] ToPackedRationalCoord(double val) { byte[] ret = new Byte[24]; UInt32[] vals = new UInt32[3]; UInt32[] denoms = new UInt32[3]; double dAbsX = Math.Abs(val); double dFloorX = Math.Floor(dAbsX); double dMinX = (dAbsX - dFloorX) * 60.0; vals[0] = (uint)Math.Round(dFloorX); // deg denoms[0] = 1; vals[1] = (uint)Math.Round(Math.Floor(dMinX)); // min denoms[1] = 1; vals[2] = (uint)Math.Round(Math.Floor((dMinX - (double)vals[1]) * 60.0 * 100)); // sec denoms[2] = 100; int j = 0; for (int i = 0; i < ret.GetLength(0); i = i + BYTEJUMP_RATIONAL) { System.UInt32 numer = vals[j]; System.UInt32 denom = denoms[j]; byte[] numerBytes = BitConverter.GetBytes(numer); Array.Copy(numerBytes, 0, ret, i, 4); byte[] denomBytes = BitConverter.GetBytes(denom); Array.Copy(denomBytes, 0, ret, i + BYTEJUMP_LONG, 4); j++; } return ret; }
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) { throw new ZlibException("The stream is not readable."); } // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) { return 0; } } } if (_streamMode != StreamMode.Reader) { throw new ZlibException("Cannot Read after Writing."); } if (count == 0) { return 0; } if (nomoreinput && _wantCompress) { return 0; // workitem 8557 } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (offset < buffer.GetLowerBound(0)) { throw new ArgumentOutOfRangeException("offset"); } if ((offset + count) > buffer.GetLength(0)) { throw new ArgumentOutOfRangeException("count"); } int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) { nomoreinput = true; } } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) { return 0; } if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); } if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) { break; // nothing more to read } } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) { crc.SlurpBlock(buffer, offset, rc); } return rc; }
public static bool IsEqual(this Int32[][] a, Byte[][] b, Int32 atol = 0, Double rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; if (rtol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (A == B) continue; var C = A; var D = B; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (A == B) continue; var C = A; var D = B; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (A != B) return false; } } return true; }
public static bool IsEqual(this sbyte[,] a, Byte[,] b, Byte atol = 0, Double rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; unsafe { fixed (sbyte* ptrA = a) fixed (Byte* ptrB = b) { if (rtol > 0) { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (A == B) continue; var C = A; var D = B; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (A == B) continue; var C = A; var D = B; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (A != B) return false; } } } } return true; }
/// <summary> /// 实现Sauvola算法实现图像二值化 /// </summary> /// <param name="bin_image">用于存储二值化完成的图像</param> /// <param name="gray_image">用于存储等待二值化完成的灰度图像</param> public static Byte[,] Sauvola(Byte[,] gray_image) { //以当前像素点为中心的邻域的宽度 int w = 40; //使用者自定义的修正系数 double k = 0.3; //邻域边界距离中心点的距离 int whalf = w >> 1; int MAXVAL = 256; int image_width = gray_image.GetLength(0); int image_height = gray_image.GetLength(1); Byte[,] bin_image = new Byte[image_width, image_height]; int[,] integral_image = new int[image_width, image_height]; int[,] integral_sqimg = new int[image_width, image_height]; int[,] rowsum_image = new int[image_width, image_height]; int[,] rowsum_sqimg = new int[image_width, image_height]; int xmin,ymin,xmax,ymax; double diagsum,idiagsum,diff,sqdiagsum,sqidiagsum,sqdiff,area; double mean,std,threshold; for (int j = 0; j < image_height; j++) { rowsum_image[0, j] = gray_image[0, j]; rowsum_sqimg[0, j] = gray_image[0, j] * gray_image[0, j]; } for (int i = 1; i < image_width; i++) { for (int j = 0; j < image_height; j++) { //计算图像范围内任意宽度窗口(邻域)的灰度值之和 rowsum_image[i, j] = rowsum_image[i - 1, j] + gray_image[i, j]; //计算图像范围内任意宽度窗口(邻域)的灰度值平方之和 rowsum_sqimg[i, j] = rowsum_sqimg[i - 1, j] + gray_image[i, j] * gray_image[i, j]; } } for (int i = 0; i < image_width; i++) { integral_image[i, 0] = rowsum_image[i, 0]; integral_sqimg[i, 0] = rowsum_sqimg[i, 0]; } for (int i = 0; i < image_width; i++) { for (int j = 1; j < image_height; j++) { //计算图像范围内任意宽度窗口(邻域)的灰度值的积分 integral_image[i, j] = integral_image[i, j - 1] + rowsum_image[i, j]; //计算图像范围内任意宽度窗口(邻域)的灰度值平方的积分 integral_sqimg[i, j] = integral_sqimg[i, j - 1] + rowsum_sqimg[i, j]; } } //Calculate the mean and standard deviation using the integral image for(int i=0; i<image_width; i++){ for(int j=0; j<image_height; j++){ xmin = Math.Max(0,i-whalf); ymin = Math.Max(0, j - whalf); xmax = Math.Min(image_width - 1, i + whalf); ymax = Math.Min(image_height - 1, j + whalf); area = (xmax-xmin+1)*(ymax-ymin+1); // area can't be 0 here // proof (assuming whalf >= 0): // we'll prove that (xmax-xmin+1) > 0, // (ymax-ymin+1) is analogous // It's the same as to prove: xmax >= xmin // image_width - 1 >= 0 since image_width > i >= 0 // i + whalf >= 0 since i >= 0, whalf >= 0 // i + whalf >= i - whalf since whalf >= 0 // image_width - 1 >= i - whalf since image_width > i // --IM if (area <= 0) throw new Exception("Binarize: area can't be 0 here"); if (xmin == 0 && ymin == 0) { // Point at origin diff = integral_image[xmax, ymax]; sqdiff = integral_sqimg[xmax, ymax]; } else if (xmin == 0 && ymin > 0) { // first column diff = integral_image[xmax, ymax] - integral_image[xmax, ymin - 1]; sqdiff = integral_sqimg[xmax, ymax] - integral_sqimg[xmax, ymin - 1]; } else if (xmin > 0 && ymin == 0) { // first row diff = integral_image[xmax, ymax] - integral_image[xmin - 1, ymax]; sqdiff = integral_sqimg[xmax, ymax] - integral_sqimg[xmin - 1, ymax]; } else { // rest of the image diagsum = integral_image[xmax, ymax] + integral_image[xmin - 1, ymin - 1]; idiagsum = integral_image[xmax, ymin - 1] + integral_image[xmin - 1, ymax]; //以(i,j)为中心点的w邻域内灰度值的积分 diff = diagsum - idiagsum; sqdiagsum = integral_sqimg[xmax, ymax] + integral_sqimg[xmin - 1, ymin - 1]; sqidiagsum = integral_sqimg[xmax, ymin - 1] + integral_sqimg[xmin - 1, ymax]; //以(i,j)为中心点的w邻域内灰度值平方的积分 sqdiff = sqdiagsum - sqidiagsum; } //以(i,j)为中心点的w邻域内的灰度均值 mean = diff/area; //以(i,j)为中心点的w邻域内的标准方差 std = Math.Sqrt((sqdiff - diff*diff/area)/(area-1)); //根据Sauvola计算公式和以(i,j)为中心点的w邻域内的灰度均值与标准方差来计算当前点(i,j)的二值化阈值 threshold = mean*(1+k*((std/128)-1)); //根据当前点的阈值对当前像素点进行二值化 if(gray_image[i,j] < threshold) bin_image[i,j] = 0; else bin_image[i,j] = (byte)(MAXVAL-1); } } return bin_image; }
public static String ToString(Byte[] value, String charset) { return Encoding.GetEncoding(charset).GetString(value, 0, value.GetLength(0)); }
/// <summary> /// 将灰度数组转换为灰度图像(256级灰度) /// </summary> /// <param name="grayArray">灰度数组</param> /// <returns>灰度图像</returns> public static Bitmap GrayArrayToGrayBitmap(Byte[,] grayArray) { // 将灰度数组转换为灰度数据 Int32 PixelHeight = grayArray.GetLength(0); // 图像高度 Int32 PixelWidth = grayArray.GetLength(1); // 图像宽度 Int32 Stride = ((PixelWidth + 3) >> 2) << 2; // 跨距宽度 Byte[] Pixels = new Byte[PixelHeight * Stride]; for (Int32 i = 0; i < PixelHeight; i++) { Int32 Index = i * Stride; for (Int32 j = 0; j < PixelWidth; j++) { Pixels[Index++] = grayArray[i, j]; } } // 创建灰度图像 Bitmap GrayBmp = new Bitmap(PixelWidth, PixelHeight, PixelFormat.Format8bppIndexed); // 设置调色表 ColorPalette cp = GrayBmp.Palette; for (int i = 0; i < 256; i++) cp.Entries[i] = Color.FromArgb(i, i, i); GrayBmp.Palette = cp; // 设置位图图像特性 BitmapData GrayBmpData = GrayBmp.LockBits(new Rectangle(0, 0, PixelWidth, PixelHeight), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); Marshal.Copy(Pixels, 0, GrayBmpData.Scan0, Pixels.Length); GrayBmp.UnlockBits(GrayBmpData); return GrayBmp; }
private string GetString(Byte[] bytes) { return encoding.GetString(bytes, 0, bytes.GetLength(0)); }
static void sendFin(IPAddress dest, int port, string plaintext) { UdpClient client = new UdpClient(); Byte[] sendBytes = new Byte[1024]; try { client.Connect(dest, port); sendBytes = Encoding.ASCII.GetBytes("FIN" + plaintext); client.Send(sendBytes, sendBytes.GetLength(0)); Console.WriteLine("Sent FIN and payload to server"); } catch (Exception e) { Console.WriteLine("Error with the Server Name: {0}", e.ToString()); } }
public static String ToString(Byte[] value) { return UTF8.GetString(value, 0, value.GetLength(0)); }
/// <summary> /// 受信コマンド解析 /// </summary> /// <returns></returns> public string TCP_ReciveCommand() { if (null == objTCPSC) return ""; System.Net.Sockets.TcpClient objSck = objTCPSC.SckProperty; System.Net.Sockets.NetworkStream objStm = objTCPSC.MyProperty; string readStr = ""; if (objStm != null && objSck != null) { // ソケット受信 if (objSck.Available > 0 && objStm.DataAvailable) { Byte[] dat = new Byte[objSck.Available]; if (0 == objStm.Read(dat, 0, dat.GetLength(0))) { // 切断を検知 objTCPSC.Dispose(); return ""; } readStr = System.Text.Encoding.GetEncoding("SHIFT-JIS").GetString(dat); hwResiveStr += readStr; { string[] rsvCmd = readStr.Split('$'); for (int i = 0; i < rsvCmd.Length; i++) { if (rsvCmd[i].Length <= 3) continue; // ロータリーエンコーダから 速度を計算 if (rsvCmd[i].Substring(0, 3) == "A1,") { const double tiyeSize = 140.0; // タイヤ直径 [mm] const double OnePuls = 250.0; // 一周のパルス数 double ResiveMS; double ResReR, ResReL; string[] splStr = rsvCmd[i].Split(','); // 0 A1 double.TryParse(splStr[1], out ResiveMS); // 小数点付き 秒 double.TryParse(splStr[2], out ResReR); // Right Wheel double.TryParse(splStr[3], out ResReL); // Left Wheel // 0.5秒以上の経過時間があれば計算 (あまりに瞬間的な値では把握しにくいため) if ((ResiveMS - oldResiveMS) > 0.5) { // 速度計算(非動輪を基準) SpeedMH = (int)(((double)(hwRErotR - oldWheelR) / OnePuls * (Math.PI * tiyeSize)) / (ResiveMS - oldResiveMS)); oldResiveMS = ResiveMS; oldWheelR = hwRErotR; } // 初回のパルス値リセット if(bInitRePulse) { ReInitR = ResReR; ReInitL = ResReL; bInitRePulse = false; } // 初回からの変化値 hwRErotR = ResReR - ReInitR; hwRErotL = ResReL - ReInitL; bhwRE = true; } else if (rsvCmd[i].Substring(0, 3) == "A2,") { // コンパス情報 // A2,22.5068,210$ double ResiveMS; int ResiveCmp; string[] splStr = rsvCmd[i].Split(','); // splStr[0] "A2" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える int.TryParse(splStr[2], out ResiveCmp); // デジタルコンパス値 hwCompass = ResiveCmp; bhwCompass = true; } else if (rsvCmd[i].Substring(0, 3) == "A3,") { // GPS情報 // $A3,38.266,36.8002,140.11559$ double ResiveMS; double ResiveLandX; // 緯度 double ResiveLandY; // 経度 string[] splStr = rsvCmd[i].Split(','); // データが足らないことがある if (splStr.Length >= 4) { // splStr[0] "A3" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える double.TryParse(splStr[2], out ResiveLandX); // GPS値 double.TryParse(splStr[3], out ResiveLandY); hwGPS_LandX = ResiveLandX; hwGPS_LandY = ResiveLandY; bhwGPS = true; bhwUsbGPS = false; } } else if (rsvCmd[i].Substring(0, 3) == "A4,") { // ロータリーエンコーダ プロット座標 // 開始時 真北基準 /* * コマンド A4 ↓ 戻り値 A4,絶対座標X,絶対座標Y,絶対座標上での向きR$ 絶対座標X[mm] 絶対座標Y[mm] 絶対座標上での向き[rad] -2π~2π 浮動小数点です。 */ double ResiveMS; double ResiveX; double ResiveY; double ResiveRad; string[] splStr = rsvCmd[i].Split(','); // splStr[0] "A4" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える double.TryParse(splStr[2], out ResiveX); // 絶対座標X mm double.TryParse(splStr[3], out ResiveY); // 絶対座標Y mm double.TryParse(splStr[4], out ResiveRad); // 向き -2PI 2PI // 座標系変換 // 右上から右下へ #if true // 座標軸を変換 ResiveY = -ResiveY; //ResiveRad = -ResiveRad; // リセットした時点での電子コンパスの向きを元にマップ座標へ変換する // x*cos - y*sin // x*sin + y*cos { hwREDir = ((-ResiveRad * 180.0) / Math.PI) + hwREStartDir; double theta = hwREStartDir / 180.0 * Math.PI; hwREX = (ResiveX * Math.Cos(theta) - ResiveY * Math.Sin(theta)) + hwREStartX; hwREY = (ResiveX * Math.Sin(theta) + ResiveY * Math.Cos(theta)) + hwREStartY; } #else hwREDir = ((-ResiveRad * 180.0) / Math.PI); hwREX = ResiveX; hwREY = ResiveY; #endif bhwREPlot = true; } } } } } return readStr; }
public static String ToString(Byte[] value, Encoding encoding) { return encoding.GetString(value, 0, value.GetLength(0)); }
public static bool IsEqual(this Decimal[][] a, Byte[][] b, Decimal atol = 0, Decimal rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; if (rtol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; decimal C = (decimal)A; decimal D = (decimal)B; if (C == D) continue; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; decimal C = (decimal)A; decimal D = (decimal)B; if (C == D) continue; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = (decimal)a[i][j]; var B = (decimal)b[i][j]; if (A != B) return false; } } return true; }