C # Comment lire les 4 premiers et les 4 derniers bits d'octets? P>
4 Réponses :
Utiliser Bitwise et code> et décalage, comme celui-ci:
byte b = 0xAB;
var low = b & 0x0F;
var high = b >> 4;
Est-ce nécessaire et éteindre les 4 bits les plus élevés après le passage?
@Martinjames vous êtes correct, et code> éteint le reste n'est pas nécessaire, car c # ne fait pas de soupire étend les octets . Merci!
dans une structure pratique:
Si vous avez besoin d'utiliser un tableau de ces demi-octets, cela simplifiera l'accès: P>
public class HalvedByteArray { public int Capacity { get; private set; } public HalvedByte[] Array { get; private set; } public byte this[int index] { get { if (index < 0 || index >= Capacity) { throw new IndexOutOfRangeException(); } var hb = Array[index / 2]; return (index % 2 == 0) ? hb.Low : hb.High; } set { if (index < 0 || index >= Capacity) { throw new IndexOutOfRangeException(); } var hb = Array[index / 2]; if (index % 2 == 0) { hb.Low = value; } else { hb.High = value; } } } public HalvedByteArray(int capacity) { if (capacity < 0) { throw new ArgumentException("Capacity must be positive.", "capacity"); } Capacity = capacity; Array = new HalvedByte[capacity / 2]; } }
Je préférerais simplement utiliser cela -
byte a = 68; byte high_bits = a>>4; byte low_bits = a&15;
Méthode simple pour le faire.
Exemple Utilisez: P>
A: 10101110 P>
B: 00001110 P>
Obtenez 4 bits de la dernière Cette sortie est comme B P>
GetBitRange (10101110, 0, 4); P>
//gets a bits from a byte, and return a byte of the new bits byte getBitRange(byte data, int start, int _end){ //shift binary to starting point of range byte shifted = (data >> start); //calculate range length (+1 for 0 index) int rangeLength = (_end-start)+1; //get binary mask based on range length byte maskBinary; switch (rangeLength){ case 1: maskBinary = 0b00000001; break; case 2: maskBinary = 0b00000011; break; case 3: maskBinary = 0b00000111; break; case 4: maskBinary = 0b00001111; break; case 5: maskBinary = 0b00011111; break; case 6: maskBinary = 0b00111111; break; case 7: maskBinary = 0b01111111; break; case 8: maskBinary = 0b11111111; break; default: // default statements Serial.println("Error: Range length too long!!"); } //cancel out byte finalByte = (shifted & maskBinary); return finalByte; }
Ce code a été écrit en C, mais avec des modifications mineures, elle fonctionnera pour C #
Veuillez poster le code que vous avez essayé et expliquer où vous êtes coincé.
Je n'ai aucun code, je dois juste savoir comment
Eh bien, nous espérons I> certains efforts ici avant que la question soit postée et que la question indique l'effort.