CHSAddress.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Copyright (C) 2014 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. namespace DiskAccessLibrary
  11. {
  12. public partial class CHSAddress
  13. {
  14. public byte Head; // the range for head is 0 through 255 inclusive
  15. public byte Sector; // The range for sector is 1 through 63
  16. public ushort Cylinder; // the range for cylinder is 0 through 1023
  17. public CHSAddress()
  18. {
  19. }
  20. public CHSAddress(byte[] buffer, int offset)
  21. {
  22. Head = buffer[offset + 0];
  23. Sector = (byte)(buffer[offset + 1] & 0x3F);
  24. // bits 7–6 of address[offset + 1] are high bits of cylinder
  25. Cylinder = (ushort)(((buffer[offset + 1] >> 6) << 8) | buffer[offset + 2]);
  26. }
  27. public void WriteBytes(byte[] buffer, int offset)
  28. {
  29. buffer[offset + 0] = Head;
  30. buffer[offset + 1] = (byte)((Sector & 0x3F) | ((Cylinder >> 8) << 6));
  31. buffer[offset + 2] = (byte)(Cylinder & 0xFF);
  32. }
  33. public static CHSAddress FromLBA(ulong lba, Disk disk)
  34. {
  35. if (disk is IDiskGeometry)
  36. {
  37. return FromLBA(lba, (IDiskGeometry)disk);
  38. }
  39. else
  40. {
  41. throw new NotImplementedException("Disk image lba to chs");
  42. }
  43. }
  44. // tracksPerCylinder a.k.a. heads per cylinder
  45. public static CHSAddress FromLBA(ulong lba, IDiskGeometry disk)
  46. {
  47. CHSAddress chs = new CHSAddress();
  48. chs.Cylinder = (ushort)(lba / (ulong)(disk.SectorsPerTrack * disk.TracksPerCylinder));
  49. chs.Head = (byte)((lba / (ulong)disk.SectorsPerTrack) % (ulong)disk.TracksPerCylinder);
  50. chs.Sector = (byte)(lba % (ulong)disk.SectorsPerTrack + 1);
  51. return chs;
  52. }
  53. }
  54. }