Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program {
- static void Main(string[] args) {
- byte[] byteArray = new byte[16];
- float value = float.Parse(Console.ReadLine());
- Console.Clear();
- Console.WriteLine("Value = {0}", value);
- GetBytes(byteArray, 1, value);
- Console.WriteLine("Byte Array = {0}", string.Join(" ", byteArray.Select(x => x.ToString("X")).ToArray()));
- float anotherValue;
- FromBytes(byteArray, 1, out anotherValue);
- Console.WriteLine("AnotherValue = {0}", anotherValue);
- anotherValue = BitConverter.ToSingle(byteArray, 1);
- Console.WriteLine("AnotherValue = {0}", anotherValue);
- Console.ReadKey();
- }
- //Maneira facil de entender
- static unsafe byte[] ToByteArray(float value) {
- byte* valuePtr = (byte*)&value;
- byte[] result = new byte[sizeof(float)];
- for(int i = 0; i < result.Length; i++)
- result[i] = *valuePtr++;
- return result;
- }
- static unsafe float FromByteArray(byte[] arr) {
- float result;
- byte* resultPtr = (byte*)&result;
- for(int i = 0; i < sizeof(float); i++)
- *(resultPtr++) = arr[i];
- return result;
- }
- //Maneira mais avançada
- static unsafe void GetBytes(byte[] array, uint offset, int value) {
- if(array == null)
- throw new ArgumentNullException("array");
- if(array.Length < offset + sizeof(int))
- throw new ArgumentOutOfRangeException("offset");
- fixed(byte* arrPtr = array)
- *((int*)(arrPtr + offset)) = value;
- }
- /*
- static unsafe void GetBytes(byte[] array, uint offset, int value) {
- if(array == null)
- throw new ArgumentNullException("array");
- if(array.Length < offset + sizeof(int))
- throw new ArgumentOutOfRangeException("offset");
- fixed(byte* arrPtr = &array[offset]) {
- int* valPtr = (int*)arrPtr;
- *valPtr = value;
- }
- }
- */
- static unsafe void GetBytes(byte[] array, uint offset, float value) {
- GetBytes(array, offset, *(int*)&value);
- }
- static unsafe void FromBytes(byte[] array, uint offset, out int value) {
- if(array == null)
- throw new ArgumentNullException("array");
- if(array.Length < offset + sizeof(int))
- throw new ArgumentOutOfRangeException("offset");
- fixed(byte* arrPtr = array)
- value = *((int*)(arrPtr + offset));
- }
- static unsafe void FromBytes(byte[] array, uint offset, out float value) {
- if(array == null)
- throw new ArgumentNullException("array");
- if(array.Length < offset + sizeof(int))
- throw new ArgumentOutOfRangeException("offset");
- fixed (byte* arrPtr = array)
- value = *((float*)(arrPtr + offset));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement