VBnet Accessing individual bits of a byte // BitArray length & count are equal to the byte value?2019 Community Moderator ElectionIndexOutOfRangeException in VB.NETCounting bits set in a .Net BitArray ClassHow to correctly get a size in bytes from a size in bits?reading bit values from bitset and transfering to byte arrayoledb exception was unhandledC# Bit ordering in byte and BitArrayFast throw unhandled exceptions in TPLVB.NET variable checkBitArray conversions and data lengths“Response received is incomplete”
If I receive an SOS signal, what is the proper response?
Coax or bifilar choke
Bash script should only kill those instances of another script's that it has launched
Hotkey (or other quick way) to insert a keyframe for only one component of a vector-valued property?
Is compression "encryption" under FCC regs?
When a wind turbine does not produce enough electricity how does the power company compensate for the loss?
Intuition behind counterexample of Euler's sum of powers conjecture
Should I tell my boss the work he did was worthless
At what distance can a bugbear, holding a reach weapon, with Polearm Mastery, get their Opportunity Attack?
Why was Goose renamed from Chewie for the Captain Marvel film?
Difference on montgomery curve equation between EFD and RFC7748
In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?
Why is computing ridge regression with a Cholesky decomposition much quicker than using SVD?
Could you please stop shuffling the deck and play already?
Does "Until when" sound natural for native speakers?
'The literal of type int is out of range' con número enteros pequeños (2 dígitos)
What are the practical Opportunty Attack values for a bugbear, holding a reach weapon, with Polearm Mastery?
Variety of conjugacy classes
What is the magic ball of every day?
Vocabulary for giving just numbers, not a full answer
How does one describe somebody who is bi-racial?
Sort with one element at the end
Why doesn't this Google Translate ad use the word "Translation" instead of "Translate"?
When stopping and starting a tile job, what to do with the extra thinset from previous row's cleanup?
VBnet Accessing individual bits of a byte // BitArray length & count are equal to the byte value?
2019 Community Moderator ElectionIndexOutOfRangeException in VB.NETCounting bits set in a .Net BitArray ClassHow to correctly get a size in bytes from a size in bits?reading bit values from bitset and transfering to byte arrayoledb exception was unhandledC# Bit ordering in byte and BitArrayFast throw unhandled exceptions in TPLVB.NET variable checkBitArray conversions and data lengths“Response received is incomplete”
I'm trying to communicate with a PLC that accepts/sends 16-bit values, with each single bit allowing for a check to happen or not.
To do this, I've been attempting to use the .Net BitArray but the results have been anything but succesful.
The underlaying structure is made out of an array of two bytes, both bytes are initialised with the value 0.
When I create a new bitarray using one of these bytes, I expected to get an array with 8 values set to false. This is not the case.
With a byte value of 0, the length and count of the bitarray is also zero. While I could presume that leading zeros are dropped, this seems very counterintuitive.
When I create a bitarray using a byte with the value of 200, I expected to get an array with 8 values (True, True, False, False, True, False, False, False). However, I instead get a bitarray with a length and count of 200?
Code is currently this :
Private FaultBits as Byte = 0
Public Sub SetBitValue(index As Integer, value As Boolean)
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
'If BitConverter.IsLittleEndian Then
'ToDo
'End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8 'Truncates incorrectly
bitArray_Section.Item(index) = value 'Set the individual bit
FaultBits = ConvertToByte(bitArray_Section) 'Set back to byte
Catch ex As Exception
Throw New Exception("clsFaultBits : SetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Sub
And the get-equivalent :
Public Function GetBitValue(index As Integer) As Boolean
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8
Return bitArray_Section.Item(index)
Catch ex As Exception
Throw New Exception("clsFaultBits : GetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Function
The convert function, I assumed this would have a length of 8 which is wrong :
Public Function ConvertToByte(bits As BitArray) As Byte
Try
If bits.Count <> 8 Then
Throw New Exception("Invalid amount of bits!")
End If
Dim returnbyte(1) As Byte
bits.CopyTo(returnbyte, 0)
Return returnbyte(0)
Catch ex As Exception
Throw New Exception("clsFaultBits : ConvertToByte : Exception : " & ex.Message())
End Try
End Function
ByteValue :: BitarrayLength / Count
0 :: 0 / 0
200 :: 200 / 200
10 :: 10 / 10
What I would like to accomplish :
Receive a byte (1-0-0-1-0-0-1-0)
Enable the booleans in the program by reading the individual bits:
Check1, Check4, Check7
Set the individual bits of the output Byte starting at 0-0-0-0-0-0-0-0
Turn on 5 : 0-0-0-0-1-0-0-0
Turn on 2 : 0-1-0-0-1-0-0-0
Send Byte
Am I completely misusing the BitArray class? What am I doing wrong?
What would allow me to change individual bit values without running into this chaos?
Why is the length / count of the BitArray the same value as the Byte, instead of the amount of bits the Byte is composed of?
I am aware the code has yet to take in account endian-ness.
Thanks in advance,
SOLVED :
I did not realise that sending a non-array byte to the BitArray would implicitly cast it to an integer and therefore it creates a BitArray which has a length/count equal to value of the byte. Which now makes complete sense.
It also made me realise my compiler warning for implicit casting does not trigger because Byte to Integer is not regarded as implicit, since I'm usually notified whenever an implicit cast happens.
Thanks for the help!
vb.net byte bitarray
add a comment |
I'm trying to communicate with a PLC that accepts/sends 16-bit values, with each single bit allowing for a check to happen or not.
To do this, I've been attempting to use the .Net BitArray but the results have been anything but succesful.
The underlaying structure is made out of an array of two bytes, both bytes are initialised with the value 0.
When I create a new bitarray using one of these bytes, I expected to get an array with 8 values set to false. This is not the case.
With a byte value of 0, the length and count of the bitarray is also zero. While I could presume that leading zeros are dropped, this seems very counterintuitive.
When I create a bitarray using a byte with the value of 200, I expected to get an array with 8 values (True, True, False, False, True, False, False, False). However, I instead get a bitarray with a length and count of 200?
Code is currently this :
Private FaultBits as Byte = 0
Public Sub SetBitValue(index As Integer, value As Boolean)
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
'If BitConverter.IsLittleEndian Then
'ToDo
'End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8 'Truncates incorrectly
bitArray_Section.Item(index) = value 'Set the individual bit
FaultBits = ConvertToByte(bitArray_Section) 'Set back to byte
Catch ex As Exception
Throw New Exception("clsFaultBits : SetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Sub
And the get-equivalent :
Public Function GetBitValue(index As Integer) As Boolean
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8
Return bitArray_Section.Item(index)
Catch ex As Exception
Throw New Exception("clsFaultBits : GetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Function
The convert function, I assumed this would have a length of 8 which is wrong :
Public Function ConvertToByte(bits As BitArray) As Byte
Try
If bits.Count <> 8 Then
Throw New Exception("Invalid amount of bits!")
End If
Dim returnbyte(1) As Byte
bits.CopyTo(returnbyte, 0)
Return returnbyte(0)
Catch ex As Exception
Throw New Exception("clsFaultBits : ConvertToByte : Exception : " & ex.Message())
End Try
End Function
ByteValue :: BitarrayLength / Count
0 :: 0 / 0
200 :: 200 / 200
10 :: 10 / 10
What I would like to accomplish :
Receive a byte (1-0-0-1-0-0-1-0)
Enable the booleans in the program by reading the individual bits:
Check1, Check4, Check7
Set the individual bits of the output Byte starting at 0-0-0-0-0-0-0-0
Turn on 5 : 0-0-0-0-1-0-0-0
Turn on 2 : 0-1-0-0-1-0-0-0
Send Byte
Am I completely misusing the BitArray class? What am I doing wrong?
What would allow me to change individual bit values without running into this chaos?
Why is the length / count of the BitArray the same value as the Byte, instead of the amount of bits the Byte is composed of?
I am aware the code has yet to take in account endian-ness.
Thanks in advance,
SOLVED :
I did not realise that sending a non-array byte to the BitArray would implicitly cast it to an integer and therefore it creates a BitArray which has a length/count equal to value of the byte. Which now makes complete sense.
It also made me realise my compiler warning for implicit casting does not trigger because Byte to Integer is not regarded as implicit, since I'm usually notified whenever an implicit cast happens.
Thanks for the help!
vb.net byte bitarray
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
Well to check if a certain bit is set in a number, you can do this:Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30
add a comment |
I'm trying to communicate with a PLC that accepts/sends 16-bit values, with each single bit allowing for a check to happen or not.
To do this, I've been attempting to use the .Net BitArray but the results have been anything but succesful.
The underlaying structure is made out of an array of two bytes, both bytes are initialised with the value 0.
When I create a new bitarray using one of these bytes, I expected to get an array with 8 values set to false. This is not the case.
With a byte value of 0, the length and count of the bitarray is also zero. While I could presume that leading zeros are dropped, this seems very counterintuitive.
When I create a bitarray using a byte with the value of 200, I expected to get an array with 8 values (True, True, False, False, True, False, False, False). However, I instead get a bitarray with a length and count of 200?
Code is currently this :
Private FaultBits as Byte = 0
Public Sub SetBitValue(index As Integer, value As Boolean)
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
'If BitConverter.IsLittleEndian Then
'ToDo
'End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8 'Truncates incorrectly
bitArray_Section.Item(index) = value 'Set the individual bit
FaultBits = ConvertToByte(bitArray_Section) 'Set back to byte
Catch ex As Exception
Throw New Exception("clsFaultBits : SetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Sub
And the get-equivalent :
Public Function GetBitValue(index As Integer) As Boolean
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8
Return bitArray_Section.Item(index)
Catch ex As Exception
Throw New Exception("clsFaultBits : GetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Function
The convert function, I assumed this would have a length of 8 which is wrong :
Public Function ConvertToByte(bits As BitArray) As Byte
Try
If bits.Count <> 8 Then
Throw New Exception("Invalid amount of bits!")
End If
Dim returnbyte(1) As Byte
bits.CopyTo(returnbyte, 0)
Return returnbyte(0)
Catch ex As Exception
Throw New Exception("clsFaultBits : ConvertToByte : Exception : " & ex.Message())
End Try
End Function
ByteValue :: BitarrayLength / Count
0 :: 0 / 0
200 :: 200 / 200
10 :: 10 / 10
What I would like to accomplish :
Receive a byte (1-0-0-1-0-0-1-0)
Enable the booleans in the program by reading the individual bits:
Check1, Check4, Check7
Set the individual bits of the output Byte starting at 0-0-0-0-0-0-0-0
Turn on 5 : 0-0-0-0-1-0-0-0
Turn on 2 : 0-1-0-0-1-0-0-0
Send Byte
Am I completely misusing the BitArray class? What am I doing wrong?
What would allow me to change individual bit values without running into this chaos?
Why is the length / count of the BitArray the same value as the Byte, instead of the amount of bits the Byte is composed of?
I am aware the code has yet to take in account endian-ness.
Thanks in advance,
SOLVED :
I did not realise that sending a non-array byte to the BitArray would implicitly cast it to an integer and therefore it creates a BitArray which has a length/count equal to value of the byte. Which now makes complete sense.
It also made me realise my compiler warning for implicit casting does not trigger because Byte to Integer is not regarded as implicit, since I'm usually notified whenever an implicit cast happens.
Thanks for the help!
vb.net byte bitarray
I'm trying to communicate with a PLC that accepts/sends 16-bit values, with each single bit allowing for a check to happen or not.
To do this, I've been attempting to use the .Net BitArray but the results have been anything but succesful.
The underlaying structure is made out of an array of two bytes, both bytes are initialised with the value 0.
When I create a new bitarray using one of these bytes, I expected to get an array with 8 values set to false. This is not the case.
With a byte value of 0, the length and count of the bitarray is also zero. While I could presume that leading zeros are dropped, this seems very counterintuitive.
When I create a bitarray using a byte with the value of 200, I expected to get an array with 8 values (True, True, False, False, True, False, False, False). However, I instead get a bitarray with a length and count of 200?
Code is currently this :
Private FaultBits as Byte = 0
Public Sub SetBitValue(index As Integer, value As Boolean)
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
'If BitConverter.IsLittleEndian Then
'ToDo
'End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8 'Truncates incorrectly
bitArray_Section.Item(index) = value 'Set the individual bit
FaultBits = ConvertToByte(bitArray_Section) 'Set back to byte
Catch ex As Exception
Throw New Exception("clsFaultBits : SetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Sub
And the get-equivalent :
Public Function GetBitValue(index As Integer) As Boolean
Try
If index < 0 Then
Throw New Exception("Index is below zero!")
End If
If index > 7 Then
Throw New Exception("Index out of bounds! Maximum allowed index value is 7")
End If
Dim bitArray_Section As BitArray = Nothing
bitArray_Section = New BitArray(FaultBits)
'bitArray_Section.Length = 8
Return bitArray_Section.Item(index)
Catch ex As Exception
Throw New Exception("clsFaultBits : GetBitValue : w. Index " & index & " : Exception : " & ex.Message())
End Try
End Function
The convert function, I assumed this would have a length of 8 which is wrong :
Public Function ConvertToByte(bits As BitArray) As Byte
Try
If bits.Count <> 8 Then
Throw New Exception("Invalid amount of bits!")
End If
Dim returnbyte(1) As Byte
bits.CopyTo(returnbyte, 0)
Return returnbyte(0)
Catch ex As Exception
Throw New Exception("clsFaultBits : ConvertToByte : Exception : " & ex.Message())
End Try
End Function
ByteValue :: BitarrayLength / Count
0 :: 0 / 0
200 :: 200 / 200
10 :: 10 / 10
What I would like to accomplish :
Receive a byte (1-0-0-1-0-0-1-0)
Enable the booleans in the program by reading the individual bits:
Check1, Check4, Check7
Set the individual bits of the output Byte starting at 0-0-0-0-0-0-0-0
Turn on 5 : 0-0-0-0-1-0-0-0
Turn on 2 : 0-1-0-0-1-0-0-0
Send Byte
Am I completely misusing the BitArray class? What am I doing wrong?
What would allow me to change individual bit values without running into this chaos?
Why is the length / count of the BitArray the same value as the Byte, instead of the amount of bits the Byte is composed of?
I am aware the code has yet to take in account endian-ness.
Thanks in advance,
SOLVED :
I did not realise that sending a non-array byte to the BitArray would implicitly cast it to an integer and therefore it creates a BitArray which has a length/count equal to value of the byte. Which now makes complete sense.
It also made me realise my compiler warning for implicit casting does not trigger because Byte to Integer is not regarded as implicit, since I'm usually notified whenever an implicit cast happens.
Thanks for the help!
vb.net byte bitarray
vb.net byte bitarray
edited Mar 7 at 8:03
Niche
asked Mar 6 at 15:28
NicheNiche
134
134
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
Well to check if a certain bit is set in a number, you can do this:Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30
add a comment |
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
Well to check if a certain bit is set in a number, you can do this:Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
Well to check if a certain bit is set in a number, you can do this:
Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30
Well to check if a certain bit is set in a number, you can do this:
Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30
add a comment |
2 Answers
2
active
oldest
votes
I'm not sure BitArray class is what you need. Anyway you can't create a BitArray from an Integer value. The statement New BitArray(200)
, for example, will create a BitArray of 200 items all set to 0.
If you need to send 16-bit values I think it would be simpler to use UShort
(also called UInt16
) datatype instead of a BitArray and use @djv suggestion to check the single bit. To set bits you have to make use of some "binary" algebra and the And
operator. Remember to always use unsigned datatypes and be aware that bit count starts from right.
New contributor
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
add a comment |
Unfortunately BitArray does not allow you to convert to/from a 16 bit value.
However, it does work for Byte() and Integer().
So we can convert from/to a 32 bit integer and that should work just fine.
It also not clear how you have your original data. As two separate bytes, or as a single 16 bit value?
I will assume a single unsinged 16 bit value.
So we will have this code:
Sub Testset()
Dim i16 As UInt16
i16 = 255
SetBits(i16, 9, False)
SetBits(i16, 9, True)
Debug.Print(GetBits(i16, 9).ToString)
End Sub
Output from above:
00000000 11111111
00000010 11111111
True
And the two routines are:
Public Sub SetBits(ByRef My16Bits As UInt16, MyINdex As Integer, MyValue As Boolean)
' toss the passed 16 bits into a 32 bit interger
' we do this, since the conversion routines only work
' for built in primitaves ike byte() or integer().
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
My32Bits(MyINdex) = MyValue
' now convert bit array back to our 32 bit integer
My32Bits.CopyTo(My32, 0)
' now copy our 32 bit interger back to that 16 bit
My16Bits = My32(0)
For i = 15 To 0 Step -1
Debug.Write(IIf(My32Bits(i), "1", "0"))
If i = 8 Then Debug.Write(" ")
Next i
Debug.Print("")
End Sub
Public Function GetBits(My16Bits As UInt16, MyIndex As Integer) As Boolean
' convert Int16 to bit array
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
Return My32Bits(MyIndex)
End Function
Of course one would remove that loop that displays the values.
And if this had to be called a "lot" of times before you want the bit array converted one way or the other - then you might separate out the converting to a bit array as a separate routine, and the pass that to the get/set bit routines and then do a final call of code to convert the bitArrary back to the Int16 value. It really depends on how many times you expect to get/set bits. So 1 or 2 times, then above is fine. If you have to always test many bits and set many bits, then convert the value to a bit array before you call + use the two routines to set/get the value. So the code that converts to and from the bit array could be separated out as separate code.
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55026660%2fvbnet-accessing-individual-bits-of-a-byte-bitarray-length-count-are-equal-t%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
I'm not sure BitArray class is what you need. Anyway you can't create a BitArray from an Integer value. The statement New BitArray(200)
, for example, will create a BitArray of 200 items all set to 0.
If you need to send 16-bit values I think it would be simpler to use UShort
(also called UInt16
) datatype instead of a BitArray and use @djv suggestion to check the single bit. To set bits you have to make use of some "binary" algebra and the And
operator. Remember to always use unsigned datatypes and be aware that bit count starts from right.
New contributor
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
add a comment |
I'm not sure BitArray class is what you need. Anyway you can't create a BitArray from an Integer value. The statement New BitArray(200)
, for example, will create a BitArray of 200 items all set to 0.
If you need to send 16-bit values I think it would be simpler to use UShort
(also called UInt16
) datatype instead of a BitArray and use @djv suggestion to check the single bit. To set bits you have to make use of some "binary" algebra and the And
operator. Remember to always use unsigned datatypes and be aware that bit count starts from right.
New contributor
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
add a comment |
I'm not sure BitArray class is what you need. Anyway you can't create a BitArray from an Integer value. The statement New BitArray(200)
, for example, will create a BitArray of 200 items all set to 0.
If you need to send 16-bit values I think it would be simpler to use UShort
(also called UInt16
) datatype instead of a BitArray and use @djv suggestion to check the single bit. To set bits you have to make use of some "binary" algebra and the And
operator. Remember to always use unsigned datatypes and be aware that bit count starts from right.
New contributor
I'm not sure BitArray class is what you need. Anyway you can't create a BitArray from an Integer value. The statement New BitArray(200)
, for example, will create a BitArray of 200 items all set to 0.
If you need to send 16-bit values I think it would be simpler to use UShort
(also called UInt16
) datatype instead of a BitArray and use @djv suggestion to check the single bit. To set bits you have to make use of some "binary" algebra and the And
operator. Remember to always use unsigned datatypes and be aware that bit count starts from right.
New contributor
New contributor
answered Mar 6 at 22:04
A.BuonanniA.Buonanni
413
413
New contributor
New contributor
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
add a comment |
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
The odd thing is, I'm not creating it from an integer value, I'm passing a byte to the constructor? Is it interpreting the byte itself as the definition of the array size?
– Niche
Mar 7 at 7:43
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
It was exactly that, it implicitly used the value of the byte as an integer to define the length of the BitArray. Thanks.
– Niche
Mar 7 at 8:01
add a comment |
Unfortunately BitArray does not allow you to convert to/from a 16 bit value.
However, it does work for Byte() and Integer().
So we can convert from/to a 32 bit integer and that should work just fine.
It also not clear how you have your original data. As two separate bytes, or as a single 16 bit value?
I will assume a single unsinged 16 bit value.
So we will have this code:
Sub Testset()
Dim i16 As UInt16
i16 = 255
SetBits(i16, 9, False)
SetBits(i16, 9, True)
Debug.Print(GetBits(i16, 9).ToString)
End Sub
Output from above:
00000000 11111111
00000010 11111111
True
And the two routines are:
Public Sub SetBits(ByRef My16Bits As UInt16, MyINdex As Integer, MyValue As Boolean)
' toss the passed 16 bits into a 32 bit interger
' we do this, since the conversion routines only work
' for built in primitaves ike byte() or integer().
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
My32Bits(MyINdex) = MyValue
' now convert bit array back to our 32 bit integer
My32Bits.CopyTo(My32, 0)
' now copy our 32 bit interger back to that 16 bit
My16Bits = My32(0)
For i = 15 To 0 Step -1
Debug.Write(IIf(My32Bits(i), "1", "0"))
If i = 8 Then Debug.Write(" ")
Next i
Debug.Print("")
End Sub
Public Function GetBits(My16Bits As UInt16, MyIndex As Integer) As Boolean
' convert Int16 to bit array
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
Return My32Bits(MyIndex)
End Function
Of course one would remove that loop that displays the values.
And if this had to be called a "lot" of times before you want the bit array converted one way or the other - then you might separate out the converting to a bit array as a separate routine, and the pass that to the get/set bit routines and then do a final call of code to convert the bitArrary back to the Int16 value. It really depends on how many times you expect to get/set bits. So 1 or 2 times, then above is fine. If you have to always test many bits and set many bits, then convert the value to a bit array before you call + use the two routines to set/get the value. So the code that converts to and from the bit array could be separated out as separate code.
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
add a comment |
Unfortunately BitArray does not allow you to convert to/from a 16 bit value.
However, it does work for Byte() and Integer().
So we can convert from/to a 32 bit integer and that should work just fine.
It also not clear how you have your original data. As two separate bytes, or as a single 16 bit value?
I will assume a single unsinged 16 bit value.
So we will have this code:
Sub Testset()
Dim i16 As UInt16
i16 = 255
SetBits(i16, 9, False)
SetBits(i16, 9, True)
Debug.Print(GetBits(i16, 9).ToString)
End Sub
Output from above:
00000000 11111111
00000010 11111111
True
And the two routines are:
Public Sub SetBits(ByRef My16Bits As UInt16, MyINdex As Integer, MyValue As Boolean)
' toss the passed 16 bits into a 32 bit interger
' we do this, since the conversion routines only work
' for built in primitaves ike byte() or integer().
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
My32Bits(MyINdex) = MyValue
' now convert bit array back to our 32 bit integer
My32Bits.CopyTo(My32, 0)
' now copy our 32 bit interger back to that 16 bit
My16Bits = My32(0)
For i = 15 To 0 Step -1
Debug.Write(IIf(My32Bits(i), "1", "0"))
If i = 8 Then Debug.Write(" ")
Next i
Debug.Print("")
End Sub
Public Function GetBits(My16Bits As UInt16, MyIndex As Integer) As Boolean
' convert Int16 to bit array
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
Return My32Bits(MyIndex)
End Function
Of course one would remove that loop that displays the values.
And if this had to be called a "lot" of times before you want the bit array converted one way or the other - then you might separate out the converting to a bit array as a separate routine, and the pass that to the get/set bit routines and then do a final call of code to convert the bitArrary back to the Int16 value. It really depends on how many times you expect to get/set bits. So 1 or 2 times, then above is fine. If you have to always test many bits and set many bits, then convert the value to a bit array before you call + use the two routines to set/get the value. So the code that converts to and from the bit array could be separated out as separate code.
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
add a comment |
Unfortunately BitArray does not allow you to convert to/from a 16 bit value.
However, it does work for Byte() and Integer().
So we can convert from/to a 32 bit integer and that should work just fine.
It also not clear how you have your original data. As two separate bytes, or as a single 16 bit value?
I will assume a single unsinged 16 bit value.
So we will have this code:
Sub Testset()
Dim i16 As UInt16
i16 = 255
SetBits(i16, 9, False)
SetBits(i16, 9, True)
Debug.Print(GetBits(i16, 9).ToString)
End Sub
Output from above:
00000000 11111111
00000010 11111111
True
And the two routines are:
Public Sub SetBits(ByRef My16Bits As UInt16, MyINdex As Integer, MyValue As Boolean)
' toss the passed 16 bits into a 32 bit interger
' we do this, since the conversion routines only work
' for built in primitaves ike byte() or integer().
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
My32Bits(MyINdex) = MyValue
' now convert bit array back to our 32 bit integer
My32Bits.CopyTo(My32, 0)
' now copy our 32 bit interger back to that 16 bit
My16Bits = My32(0)
For i = 15 To 0 Step -1
Debug.Write(IIf(My32Bits(i), "1", "0"))
If i = 8 Then Debug.Write(" ")
Next i
Debug.Print("")
End Sub
Public Function GetBits(My16Bits As UInt16, MyIndex As Integer) As Boolean
' convert Int16 to bit array
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
Return My32Bits(MyIndex)
End Function
Of course one would remove that loop that displays the values.
And if this had to be called a "lot" of times before you want the bit array converted one way or the other - then you might separate out the converting to a bit array as a separate routine, and the pass that to the get/set bit routines and then do a final call of code to convert the bitArrary back to the Int16 value. It really depends on how many times you expect to get/set bits. So 1 or 2 times, then above is fine. If you have to always test many bits and set many bits, then convert the value to a bit array before you call + use the two routines to set/get the value. So the code that converts to and from the bit array could be separated out as separate code.
Unfortunately BitArray does not allow you to convert to/from a 16 bit value.
However, it does work for Byte() and Integer().
So we can convert from/to a 32 bit integer and that should work just fine.
It also not clear how you have your original data. As two separate bytes, or as a single 16 bit value?
I will assume a single unsinged 16 bit value.
So we will have this code:
Sub Testset()
Dim i16 As UInt16
i16 = 255
SetBits(i16, 9, False)
SetBits(i16, 9, True)
Debug.Print(GetBits(i16, 9).ToString)
End Sub
Output from above:
00000000 11111111
00000010 11111111
True
And the two routines are:
Public Sub SetBits(ByRef My16Bits As UInt16, MyINdex As Integer, MyValue As Boolean)
' toss the passed 16 bits into a 32 bit interger
' we do this, since the conversion routines only work
' for built in primitaves ike byte() or integer().
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
My32Bits(MyINdex) = MyValue
' now convert bit array back to our 32 bit integer
My32Bits.CopyTo(My32, 0)
' now copy our 32 bit interger back to that 16 bit
My16Bits = My32(0)
For i = 15 To 0 Step -1
Debug.Write(IIf(My32Bits(i), "1", "0"))
If i = 8 Then Debug.Write(" ")
Next i
Debug.Print("")
End Sub
Public Function GetBits(My16Bits As UInt16, MyIndex As Integer) As Boolean
' convert Int16 to bit array
Dim My32(0) As Integer
My32(0) = My16Bits
Dim My32Bits As New BitArray(New Integer() My32(0))
Return My32Bits(MyIndex)
End Function
Of course one would remove that loop that displays the values.
And if this had to be called a "lot" of times before you want the bit array converted one way or the other - then you might separate out the converting to a bit array as a separate routine, and the pass that to the get/set bit routines and then do a final call of code to convert the bitArrary back to the Int16 value. It really depends on how many times you expect to get/set bits. So 1 or 2 times, then above is fine. If you have to always test many bits and set many bits, then convert the value to a bit array before you call + use the two routines to set/get the value. So the code that converts to and from the bit array could be separated out as separate code.
answered Mar 7 at 1:23
Albert D. KallalAlbert D. Kallal
16.5k12338
16.5k12338
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
add a comment |
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
The data is obtained in a byte() array, though I've been looking into handling one set of 8 bits at a time since the original PLC message is in the first byte, the outgoing communication is in the second byte. I need to be able to set individual bits in both parts of the byte array. What I don't understand is : Dim myByteArray() as Byte = 0,200 Dim bitArray_Section1 as BitArray = New BitArray(myByteArray(0)) Dim bitArray_Section2 as BitArray = New BitArray(myByteArray(1)) Why is the length/count the same as the byte value? Am I not sending a primitive byte to the constructor?
– Niche
Mar 7 at 7:38
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
Solved, the Byte was casted implicitly to an integer to be used as the length of the BitArray, sending in the full array got the behaviour I needed and expected.
– Niche
Mar 7 at 8:05
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55026660%2fvbnet-accessing-individual-bits-of-a-byte-bitarray-length-count-are-equal-t%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What data type does the API of the PLC accept? Can you link to an online documentation?
– djv
Mar 6 at 15:35
@djv The PLC accepts Bytes sent via TCP/IP, it is not attached directly to the system so I don't know the exact type, I can communicate with it and receive/send bytes succesfully. The issue is more than I can't split the bytes into sets of 8 booleans that I require to know what it is trying to tell me. The BitArray class looks like what I need, but it doesn't seem to function in that regard.
– Niche
Mar 6 at 15:41
Well to check if a certain bit is set in a number, you can do this:
Dim nThBitSet As Boolean = (number And n) = n
– djv
Mar 6 at 16:30