473,385 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Manipulating bits

What is the best way to manipulate bits in a byte?
I got to a situation where I need to organize the bit's order of a byte in a big loop (I mean it), so I say "best" in every aspect, including performance.
The less convertion instructions and more cpu native ones, the better.

Let me be more specific:

I have a shift Integer() array that contains an order. Also, a buffer() byte array.

For example:

Dim shift as Integer() {2,1,0,7,5,4,6,3}
dim buffer as Byte() 'variable with data

in the case above and with a byte like 10010111, the byte should be transformed into 00110011.

take a look:

------------------------
From: 10010111
To : 00110011
------------------------

following the shift "index" order.

This seems a simple problem but the performance here is really critical. It would be great if we could do this only with Xor sort of instructions (since its low level)
Any suggestions?
May 24 '07 #1
17 1661
Plater
7,872 Expert 4TB
What do you mean organize bits?
If I have byte 0xA5 then the bits are 10100101, what do you wish to do to those bits?
May 24 '07 #2
Exactly, organize them.. I edited the 1st post. Please take a look.

I made it once concatenating strings of 1's to a StringBuilder but the performance was horrible, takes like 2 minutes to finish the loop..
cant think of any logic, if you have any ideas..

thank you!
May 24 '07 #3
What do you mean organize bits?
If I have byte 0xA5 then the bits are 10100101, what do you wish to do to those bits?
This is my current code:
Expand|Select|Wrap|Line Numbers
  1. Private Sub ShiftMe(ByVal buffer As Byte(), ByVal shift As Integer())
  2.  
  3.       'Lets shift byte's columns
  4.       Dim worker As New System.Text.StringBuilder
  5.       Dim bkupArray As Boolean()
  6.       ReDim bkupArray(7)
  7.  
  8.       For p As Integer = 0 To buffer.GetUpperBound(0)
  9.  
  10.          'Separate each bit of byte
  11.          bkupArray(0) = buffer(p) And 1
  12.          bkupArray(1) = (buffer(p) And 2) >> 1
  13.          bkupArray(2) = (buffer(p) And 4) >> 2
  14.          bkupArray(3) = (buffer(p) And 8) >> 3
  15.          bkupArray(4) = (buffer(p) And 16) >> 4
  16.          bkupArray(5) = (buffer(p) And 32) >> 5
  17.          bkupArray(6) = (buffer(p) And 64) >> 6
  18.          bkupArray(7) = (buffer(p) And 128) >> 7
  19.  
  20.          'Create Shifted byte
  21.          buffer(p) = 0 'clean old byte
  22.          worker.Remove(0, worker.Length)
  23.          worker.Append(bkupArray(shift(7)) & bkupArray(shift(6)) & bkupArray(shift(5)) & bkupArray(shift(4)) & bkupArray(shift(3)) & bkupArray(shift(2)) & bkupArray(shift(1)) & bkupArray(shift(0)))
  24.  
  25.          buffer(p) = StrToByteArray(worker.ToString)
  26.       Next
  27.  
  28.  
  29.    End Sub
  30.  
May 24 '07 #4
TRScheel
638 Expert 512MB
This is my current code:
Expand|Select|Wrap|Line Numbers
  1. Private Sub ShiftMe(ByVal buffer As Byte(), ByVal shift As Integer())
  2.  
  3.       'Lets shift byte's columns
  4.       Dim worker As New System.Text.StringBuilder
  5.       Dim bkupArray As Boolean()
  6.       ReDim bkupArray(7)
  7.  
  8.       For p As Integer = 0 To buffer.GetUpperBound(0)
  9.  
  10.          'Separate each bit of byte
  11.          bkupArray(0) = buffer(p) And 1
  12.          bkupArray(1) = (buffer(p) And 2) >> 1
  13.          bkupArray(2) = (buffer(p) And 4) >> 2
  14.          bkupArray(3) = (buffer(p) And 8) >> 3
  15.          bkupArray(4) = (buffer(p) And 16) >> 4
  16.          bkupArray(5) = (buffer(p) And 32) >> 5
  17.          bkupArray(6) = (buffer(p) And 64) >> 6
  18.          bkupArray(7) = (buffer(p) And 128) >> 7
  19.  
  20.          'Create Shifted byte
  21.          buffer(p) = 0 'clean old byte
  22.          worker.Remove(0, worker.Length)
  23.          worker.Append(bkupArray(shift(7)) & bkupArray(shift(6)) & bkupArray(shift(5)) & bkupArray(shift(4)) & bkupArray(shift(3)) & bkupArray(shift(2)) & bkupArray(shift(1)) & bkupArray(shift(0)))
  24.  
  25.          buffer(p) = StrToByteArray(worker.ToString)
  26.       Next
  27.  
  28.  
  29.    End Sub
  30.  
Heres how I would have done it:

Expand|Select|Wrap|Line Numbers
  1. private static void ByteShifting()
  2. {
  3.     //00001010 = 10
  4.     //10000000 = 128
  5.  
  6.     int[] shift = new int[] { 2, 1, 0, 7, 5, 4, 6, 3 };
  7.     byte buffer = new byte();
  8.     buffer = 10;
  9.     int[] integerArrayFromByte = GetIntegerArrayFromByte(buffer);
  10.     int[] integerArray = new int[8];
  11.  
  12.     Console.WriteLine();
  13.     Console.Write("Byte to Int Array: ");
  14.     for (int i = 0; i < integerArrayFromByte.Length; i++)
  15.     {
  16.         if (i != integerArrayFromByte.Length - 1)
  17.         {
  18.             Console.Write("{0}-", integerArrayFromByte[i]);
  19.         }
  20.         else
  21.         {
  22.             Console.Write("{0}", integerArrayFromByte[i]);
  23.         }
  24.     }
  25.     Console.WriteLine();
  26.  
  27.     for (int i = 0; i < integerArray.Length; i++)
  28.     {
  29.         integerArray[i] = integerArrayFromByte[shift[i]];
  30.     }
  31.  
  32.     Console.WriteLine();
  33.     Console.WriteLine("Bytes Shifted: {0}", GetByteFromIntegerArray(integerArray));
  34.     Console.WriteLine();
  35.  
  36.     PressAnyKeyToContinue();
  37. }
  38.  
  39. private static int[] GetIntegerArrayFromByte(byte buffer)
  40. {
  41.     List<int> integerArray = new List<int>();
  42.     //Console.WriteLine("\tCurrent Byte Value: {0}", buffer);
  43.  
  44.     for (int i = 7; i >= 0; i--)
  45.     {
  46.         if (buffer >= Math.Pow(2, i))
  47.         {
  48.             integerArray.Add(1);
  49.             buffer -= (byte)Math.Pow(2, i);
  50.         }
  51.         else
  52.         {
  53.             integerArray.Add(0);
  54.         }
  55.     }
  56.  
  57.     return integerArray.ToArray();
  58. }
  59.  
  60. private static byte GetByteFromIntegerArray(int[] integerArray)
  61. {
  62.     byte buffer = 0;
  63.  
  64.     for (int i = 0; i < integerArray.Length; i++)
  65.     {
  66.         if (integerArray[i] == 1)
  67.         {
  68.             buffer += (byte)Math.Pow(2, 7 - i);
  69.         }
  70.     }
  71.  
  72.     return buffer;
  73. }
  74.  
Didnt realize you did it in VB, be back in a few with the VB version of it...
May 24 '07 #5
Thanks a lot, I will try that code.. but would be better if was in vb ;)
May 24 '07 #6
Plater
7,872 Expert 4TB
So you want to shove the 1s to the right on each half byte?
hmm very strange thing to desire. Can I ask why you need this? Seems like a waste?

I been trying for awhile and best I got was:
Expand|Select|Wrap|Line Numbers
  1. private void bitshove(byte b)
  2. {
  3.    int n = 0;
  4.    if ((b & 0x01) == 0x01)
  5.    {
  6.        n++;
  7.    }
  8.    if ((b & 0x02) == 0x02)
  9.    {
  10.        n++;
  11.    }
  12.    if ((b & 0x04) == 0x04)
  13.    {
  14.        n++;
  15.    }
  16.    if ((b & 0x08) == 0x08)
  17.    {
  18.        n++;
  19.    }
  20.    //now n= number of 1s in the half byte
  21. }
  22.  
May 24 '07 #7
TRScheel
638 Expert 512MB
Thanks a lot, I will try that code.. but would be better if was in vb ;)
Here it is in VB

Expand|Select|Wrap|Line Numbers
  1.     Sub Main()
  2.  
  3.         '00001010 = 10
  4.         '10000000 = 128
  5.  
  6.         Dim shift() As Integer = {2, 1, 0, 7, 5, 4, 6, 3}
  7.         Dim buffer As Byte = 10
  8.         Dim integerArrayFromByte() As Integer = GetIntegerArrayFromByte(buffer)
  9.         Dim integerArray(7) As Integer
  10.  
  11.         Console.WriteLine()
  12.         Console.WriteLine("Byte to Int Array: ")
  13.         For i As Integer = 0 To integerArrayFromByte.Length - 1 Step 1
  14.             If Not (i = integerArrayFromByte.Length - 1) Then
  15.                 Console.Write("{0}-", integerArrayFromByte(i))
  16.             Else
  17.                 Console.Write("{0}", integerArrayFromByte(i))
  18.             End If
  19.         Next
  20.         Console.WriteLine()
  21.  
  22.         For i As Integer = 0 To integerArray.Length - 1 Step 1
  23.             integerArray(i) = integerArrayFromByte(shift(i))
  24.         Next
  25.  
  26.         Console.WriteLine()
  27.         Console.WriteLine("Bytes Shifted: {0}", GetByteFromIntegerArray(integerArray))
  28.         Console.WriteLine()
  29.  
  30.         PressAnyKeyToContinue()
  31.  
  32.     End Sub
  33.  
  34.     Function GetIntegerArrayFromByte(ByVal buffer As Byte) As Integer()
  35.  
  36.         Dim integerArray As List(Of Integer) = New List(Of Integer)()
  37.  
  38.         For i As Integer = 7 To 0 Step -1
  39.             If (buffer >= Math.Pow(2, i)) Then
  40.                 integerArray.Add(1)
  41.                 buffer -= Math.Pow(2, i)
  42.             Else
  43.                 integerArray.Add(0)
  44.             End If
  45.         Next
  46.  
  47.         Return integerArray.ToArray()
  48.     End Function
  49.  
  50.     Function GetByteFromIntegerArray(ByRef integerArray() As Integer) As Byte
  51.         Dim buffer As Byte = 0
  52.  
  53.         For i As Integer = 0 To integerArray.Length - 1 Step 1
  54.             If (integerArray(i) = 1) Then
  55.                 buffer += Math.Pow(2, 7 - i)
  56.             End If
  57.         Next
  58.  
  59.         Return buffer
  60.     End Function
  61.  
  62.     Sub PressAnyKeyToContinue()
  63.         Console.ReadKey(True)
  64.     End Sub
  65.  

As an aside...

This code is dirty as all hell. For one, it needs to have checks for the right size arrays being sent eveywhere. It checks no where for nulls (nothing in vb).

In addition, i would be my bottom dollar there's an easier way to grab the 1's and 0's outta a byte, but I couldnt figure it out in the 10 or so minutes that i wanted to spend on this, so you have those functions there.

Some final notes, the functions could use better names, and there is probably a way to do it without the Math.Pow as well. This WILL work faster then your string parse though.
May 24 '07 #8
So you want to shove the 1s to the right on each half byte?
hmm very strange thing to desire. Can I ask why you need this? Seems like a waste?

I been trying for awhile and best I got was:
Expand|Select|Wrap|Line Numbers
  1. private void bitshove(byte b)
  2. {
  3.    int n = 0;
  4.    if ((b & 0x01) == 0x01)
  5.    {
  6.        n++;
  7.    }
  8.    if ((b & 0x02) == 0x02)
  9.    {
  10.        n++;
  11.    }
  12.    if ((b & 0x04) == 0x04)
  13.    {
  14.        n++;
  15.    }
  16.    if ((b & 0x08) == 0x08)
  17.    {
  18.        n++;
  19.    }
  20.    //now n= number of 1s in the half byte
  21. }
  22.  
No, not like this. They must be ordered according to the variable "shift".

if I say the shift is ( 0 , 1 , 2 ,3 , 4 ,5 ,6 ,7)
and the byte is 10101010
then I would get the same 10101010

and when the order for example is ( 0 , 2 , 1 ,3 , 4 ,5 ,6 ,7 )
then the byte 10101010
would turn to be 11001010

(note that the second and third bit switched)

I think TRSCheel got the idea, Im trying to convert his code to VB and test the result. As soon as I have it I post it here.
May 24 '07 #9
ok, you were faster than me :)
I try and tell you how your code's performance came out here..
thanks a lot
Thiago.
May 24 '07 #10
TRScheel
638 Expert 512MB
So you want to shove the 1s to the right on each half byte?
hmm very strange thing to desire. Can I ask why you need this? Seems like a waste?

I been trying for awhile and best I got was:
Expand|Select|Wrap|Line Numbers
  1. private void bitshove(byte b)
  2. {
  3.    int n = 0;
  4.    if ((b & 0x01) == 0x01)
  5.    {
  6.        n++;
  7.    }
  8.    if ((b & 0x02) == 0x02)
  9.    {
  10.        n++;
  11.    }
  12.    if ((b & 0x04) == 0x04)
  13.    {
  14.        n++;
  15.    }
  16.    if ((b & 0x08) == 0x08)
  17.    {
  18.        n++;
  19.    }
  20.    //now n= number of 1s in the half byte
  21. }
  22.  
I am curious... trying to follow this logic, this does this right:

you test a byte against a byte with only the first bit as 1, and if they return exactly the same as the byte with only the first bit as 1, then the original byte has a 1, then continue... etc?

Because if so, then my code could be cleaned up quite a bit...


Hence...

0001001 & 00000001 = 00000001
0001001 & 00000010 = 00000000
0001001 & 00000100 = 00000000
0001001 & 00001000 = 00001000

correct?
May 24 '07 #11
TRScheel
638 Expert 512MB
ok, you were faster than me :)
I try and tell you how your code's performance came out here..
thanks a lot
Thiago.

Here, this will be faster:

And I think I have an order problem in the earlier ones, I ordered the bits backwards.

Expand|Select|Wrap|Line Numbers
  1.     Sub Main()
  2.         Dim shift(8) As Integer
  3.         Dim buffer As Byte
  4.         Dim newBuffer As Byte
  5.  
  6.         shift = New Integer() {2, 1, 0, 7, 5, 4, 6, 3}
  7.         buffer = 10
  8.  
  9.         newBuffer = ReArrangeBytes(buffer, shift)
  10.  
  11.         Console.WriteLine("{0}", newBuffer)
  12.         Console.ReadKey(True)
  13.     End Sub
  14.  
  15.     Function ReArrangeBytes(ByVal buffer As Byte, ByVal shift() As Integer) As Byte
  16.  
  17.         Dim result As Byte = 0
  18.  
  19.         For i As Integer = 0 To 7 Step 1
  20.             Dim ToTest As Byte = Math.Pow(2, i)
  21.             If ((buffer And ToTest) = ToTest) Then
  22.                 result += Math.Pow(2, shift(7 - i))
  23.             End If
  24.         Next
  25.  
  26.         Return result
  27.     End Function
  28.  

To Plater:

Didnt know that about the bytes. I remember learning something about it, but I dismissed it... probably shouldnt have, heh. Never really liked bytes
May 24 '07 #12
here's a c# sample that doesn't make function calls to assign the positions.
If you pass an array of bit flags 0x01, 0x02, 0x04 , etc. to represent your re-ordering instead of ordinal positions 1 to 8....

public static class X
{
[Flags]
public enum BITPOSTION :byte { NONE=0, P1 = 0x01, P2 = 0x02, P3 = 0x04, P4 = 0x08, P5 = 0x10, P6 = 0x20, P7 = 0x40, P8 = 0x80 }
public static X.BITPOSTION shift(X.BITPOSTION v, params X.BITPOSTION[] bpos)
{
X.BITPOSTION d = X.BITPOSTION.NONE;
if ((v & X.BITPOSTION.P1) == X.BITPOSTION.P1) d |= bpos[0];
if ((v & X.BITPOSTION.P2) == X.BITPOSTION.P2) d |= bpos[1];
if ((v & X.BITPOSTION.P3) == X.BITPOSTION.P3) d |= bpos[2];
if ((v & X.BITPOSTION.P4) == X.BITPOSTION.P4) d |= bpos[3];
if ((v & X.BITPOSTION.P5) == X.BITPOSTION.P5) d |= bpos[4];
if ((v & X.BITPOSTION.P6) == X.BITPOSTION.P6) d |= bpos[5];
if ((v & X.BITPOSTION.P7) == X.BITPOSTION.P7) d |= bpos[6];
if ((v & X.BITPOSTION.P8) == X.BITPOSTION.P8) d |= bpos[7];
return d;
}
}
static class Program
{
public static void Main(string[] args)
{
MyConfigSection s = (MyConfigSection)ConfigurationManager.GetSection(" myConfig");
Console.WriteLine("Level: " + s.Level + "<br>");
Console.WriteLine("Name: " + s.Name);
while (true)
{
byte ax;
X.BITPOSITION result = X.BITPOSITION.NONE;
System.Byte.TryParse(Console.ReadLine(), System.Globalization.NumberStyles.HexNumber, null,out ax);
//This is a sample of how I want to re-order my bits
X.BITPOSTION[] av = { X.BITPOSTION.P2, X.BITPOSTION.P4, X.BITPOSTION.P7, X.BITPOSTION.P1, X.BITPOSTION.P3, X.BITPOSTION.P5, X.BITPOSTION.P8, X.BITPOSTION.P6 };
result = X.shift(ax, av);
Console.WriteLine("From {0:X}({1}) to {2:X}({3}) ", ax, ax, result, result.ToString());
}
return;
}
}
May 25 '07 #13
Hey,
thanks everyone who helped me out of this problem that seemed so simple. Specially TRScheel who brought up the idea of using the Math.pow that is the core of all this I think.

Though, there is 2 little problems with the code you gave, first the corrrect operation to "add" the bits desired should be OR instead of +.

Second, the bits order are still reversed, that is because the pow(shift(7-i)) returns the positioning of the bit in Integer, causing it to be put in the left to right order, the opposite of our analisys that happens from right to left.

For example, when shift(7-i) (in the most inner loop) returns 6, that means it sould be in ( X, X ,X ,X ,X ,this, X, X) position, but 6 actually adds 100000 to the new byte, because pow(2,6) = 100000 (Note the reversed order).

in here:

Expand|Select|Wrap|Line Numbers
  1. newBuffer = newBuffer Or math.pow(2,shift(7-1))
and it doesnt help if you reverse the loop from 7 to 0, step -1 because that will just change the order we analyse the bits, therefore not affecting the final result.

The following is the code with the first problem fixed, but with the reversed order problem:

Expand|Select|Wrap|Line Numbers
  1.  For k As Integer = 0 To buffer.GetUpperBound(0)
  2.  
  3.          newBuffer = 0
  4.  
  5.          For i As Integer = 0 To 7
  6.  
  7.             If ((buffer(k) And Math.Pow(2, i)) > 0) Then
  8.  
  9.                newBuffer = newBuffer Or pos(7 - i)
  10.  
  11.             End If
  12.          Next
  13.  
  14.          buffer(k) = newBuffer
  15.  
  16.       Next
  17.  
Note: I put the buffer array in another loop, just to show the operation being processed with many bytes, but you can take that off for better clarity.

Actually I found a way around to this second problem, but I wont give the code for a while as a challange so that we can compare the solutions and check what was the best one. If no one post anything, then I post the solution I found ;)

Later,
Thiago.

PS.: oohay251, as soon as I can test your code I put the results here..tnks
May 25 '07 #14
Ok,

here is the complete code following TRScheel's logic with the pow:

Expand|Select|Wrap|Line Numbers
  1. Private Sub ShiftMe(ByVal buffer As Byte(), ByVal shift As Integer())
  2.  
  3. Dim result As Byte = 0
  4.       Dim newBuffer As Byte
  5.  
  6.       'convert shift values integer>binary - for positioning
  7.       Dim pos As Byte()
  8.       ReDim pos(7)
  9.       For m As Integer = 0 To 7
  10.          If (shift(m) = 7) Then
  11.             pos(m) = 1
  12.          ElseIf (shift(m) = 6) Then
  13.             pos(m) = 2
  14.          ElseIf (shift(m) = 5) Then
  15.             pos(m) = 4
  16.          ElseIf (shift(m) = 4) Then
  17.             pos(m) = 8
  18.          ElseIf (shift(m) = 3) Then
  19.             pos(m) = 16
  20.          ElseIf (shift(m) = 2) Then
  21.             pos(m) = 32
  22.          ElseIf (shift(m) = 1) Then
  23.             pos(m) = 64
  24.          ElseIf (shift(m) = 0) Then
  25.             pos(m) = 128
  26.          End If
  27.       Next
  28.  
  29.       For k As Integer = 0 To buffer.GetUpperBound(0)
  30.          newBuffer = 0
  31.          For i As Integer = 0 To 7
  32.             If ((buffer(k) And Math.Pow(2, i)) > 0) Then
  33.                newBuffer = newBuffer Or pos(7 - i)
  34.             End If
  35.          Next
  36.          buffer(k) = newBuffer
  37.       Next
  38. End Sub
while the code is very small I had for some reason a horrible performance with this. I made the test with a 30MB buffer and compared the time.

With the StringBuilder's code the cpu took 1' 30 seconds to finish the loop, while with the pow it took 2' 20 seconds! almost the double of time.

Any other ideas for this? maybe with the StringBuilder's logic is the best as I can get?

Note that I dont use normal string in the first example, because normal's string concatenation and operations actually creates a new string every operation. But StringBuilder is just one object optimized to be changed very often without re-creating itself like a normal string.
May 25 '07 #15
your performance is going to remain terrible as long as your making function calls for every bit position.

To test performance times, I personally would try using C or C++ to create an inline assembly routine and compile it to a library I could reference.

Also, if it fell in line with your needs, I would try re-ordering buffers of bytes at a time rather than one byte per function call.
May 25 '07 #16
TRScheel
638 Expert 512MB
Ok,

here is the complete code following TRScheel's logic with the pow:

Expand|Select|Wrap|Line Numbers
  1. Private Sub ShiftMe(ByVal buffer As Byte(), ByVal shift As Integer())
  2.  
  3. Dim result As Byte = 0
  4.       Dim newBuffer As Byte
  5.  
  6.       'convert shift values integer>binary - for positioning
  7.       Dim pos As Byte()
  8.       ReDim pos(7)
  9.       For m As Integer = 0 To 7
  10.          If (shift(m) = 7) Then
  11.             pos(m) = 1
  12.          ElseIf (shift(m) = 6) Then
  13.             pos(m) = 2
  14.          ElseIf (shift(m) = 5) Then
  15.             pos(m) = 4
  16.          ElseIf (shift(m) = 4) Then
  17.             pos(m) = 8
  18.          ElseIf (shift(m) = 3) Then
  19.             pos(m) = 16
  20.          ElseIf (shift(m) = 2) Then
  21.             pos(m) = 32
  22.          ElseIf (shift(m) = 1) Then
  23.             pos(m) = 64
  24.          ElseIf (shift(m) = 0) Then
  25.             pos(m) = 128
  26.          End If
  27.       Next
  28.  
  29.       For k As Integer = 0 To buffer.GetUpperBound(0)
  30.          newBuffer = 0
  31.          For i As Integer = 0 To 7
  32.             If ((buffer(k) And Math.Pow(2, i)) > 0) Then
  33.                newBuffer = newBuffer Or pos(7 - i)
  34.             End If
  35.          Next
  36.          buffer(k) = newBuffer
  37.       Next
  38. End Sub
while the code is very small I had for some reason a horrible performance with this. I made the test with a 30MB buffer and compared the time.

With the StringBuilder's code the cpu took 1' 30 seconds to finish the loop, while with the pow it took 2' 20 seconds! almost the double of time.

Any other ideas for this? maybe with the StringBuilder's logic is the best as I can get?

Note that I dont use normal string in the first example, because normal's string concatenation and operations actually creates a new string every operation. But StringBuilder is just one object optimized to be changed very often without re-creating itself like a normal string.

Wow, when I ran it, it took a fraction of a second.
May 30 '07 #17
TRScheel
638 Expert 512MB
Hey,
thanks everyone who helped me out of this problem that seemed so simple. Specially TRScheel who brought up the idea of using the Math.pow that is the core of all this I think.
...

Later,
Thiago.

PS.: oohay251, as soon as I can test your code I put the results here..tnks
I got this

Expand|Select|Wrap|Line Numbers
  1. Module Module1
  2.  
  3.     Sub Main()
  4.         Dim shift(8) As Integer
  5.         Dim buffer As Byte
  6.         Dim newBuffer As Byte
  7.         Dim originalTime As Long
  8.  
  9.         shift = New Integer() {2, 1, 0, 7, 5, 4, 6, 3}
  10.         buffer = 10
  11.         Console.WriteLine("{0} = {1}", GetBytes(buffer), buffer)
  12.  
  13.         originalTime = DateTime.Now.Ticks
  14.         newBuffer = ReArrangeBytes(buffer, shift)
  15.         Console.WriteLine("Elapsed Time: {0}", DateTime.Now.Ticks - originalTime)
  16.  
  17.         Console.WriteLine("{0} = {1}", GetBytes(newBuffer), newBuffer)
  18.         Console.ReadKey(True)
  19.     End Sub
  20.  
  21.     Function ReArrangeBytes(ByVal buffer As Byte, ByVal shift() As Integer) As Byte
  22.         Dim result As Byte = 0
  23.  
  24.         For i As Integer = 0 To 7 Step 1
  25.             Dim ToTest As Byte = Math.Pow(2, 7 - i)
  26.             If ((buffer And ToTest) = ToTest) Then
  27.                 result = result Or Math.Pow(2, 7 - shift(i))
  28.             End If
  29.         Next
  30.  
  31.         Return result
  32.     End Function
  33.  
  34.     Function GetBytes(ByVal buffer As Byte) As String
  35.         Dim result As String = String.Empty
  36.  
  37.         For i As Integer = 0 To 7 Step 1
  38.             Dim ToTest As Byte = Math.Pow(2, 7 - i)
  39.             If ((buffer And ToTest) = ToTest) Then
  40.                 result += "1"
  41.             Else
  42.                 result += "0"
  43.             End If
  44.         Next
  45.  
  46.         Return result
  47.     End Function
  48.  
  49. End Module
  50.  
  51.  
May 30 '07 #18

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Kristian Nybo | last post by:
Hi, I'm writing a simple image file exporter as part of a school project. To implement my image format of choice I need to work with big-endian bytes, where 'byte' of course means '8 bits', not...
2
by: James Dean | last post by:
Could anybody tell me the most efficient way to set the bits in a 1Bpp class. I am reading in byte lines of an image. The byte array tells me what what bits are turned on or off.....i do bit...
21
by: felixnielsen | last post by:
If im not mistaken, a char variable allocates 1 byte of memory, as it is the case with a bool variable. I need 2 bool and 1 char variable which only need to contain a value between 0 and 63...
29
by: Halid Umar A M | last post by:
Hi All, I m Halid Umar, network security research student. I will explain my situation and give me hint if you can. I expect reply from you all. * I have to handle numbers that have more than...
7
by: pbd22 | last post by:
Hi. How Do I "UPDATE" a previously created string? I have a problem where an XML string created in an event handler fails because the string doesn't "UPDATE" each time the event hanlder fires,...
8
by: brainflakes.org | last post by:
Hi guys, I need to manipulate binary data (8 bit) stored in a 2 dimensional array. I've tried various methods (arrays, using a string filled with chr(0), using gd lib) and so far the fastest...
8
by: HTB | last post by:
Hi, Now, if we have a String we can manipulate its basic components (Char). How about a Byte, are we able to manipulate its (Bits) one by one. I found a class Bit in Java, how about C#. ...
11
by: Mack | last post by:
Hi all, I want to write a program to count number of bits set in a number. The condition is we should not loop through each bit to find whether its set or not. Thanks in advance, -Mukesh
2
by: Allen | last post by:
I'm using Python to do some simple network programming, and found the struct module very useful for such things, but is there a way to easily manipulate bitsets such as a 16 bit word being split...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.