I'm re-writing some old application in VB.NET to C# and ASP.NET 3.5. Everything is going OK but I have this problem - and, as the database will not be changed, I must find a solution to it.
The old app saves the list o desired days (from Sunday to Saturday) in a byte. This is the way it do it:
If chkDaily.Checked Then
daysBitmask = 127 ' This is for a full week
Else
For i = 0 To chklstWeekly.Items.Count - 1
If chklstWeekly.Items(i).Selected Then
' List the selected items
daysBitmask += 2 ^ CInt(chklstWeekly.Items(i).Value)
daysBitmask = daysBitmask
Message2.InnerText = daysBitmask
End If
Next
End If
and I converted it to
if (rdbDaysList.SelectedValue == DAILY)
daysBitmask = 127;
//This is for a full week
else
foreach (var d in ckbDaysList.Items)
{
ListItem day = d as ListItem;
if (day.Selected)
{
daysBitmask += Convert.ToByte(Math.Pow(2, Convert.ToDouble(day.Value)));
}
}
This works. My biggest problem is to convert fr开发者_如何学Com the byte to the C# code. The original VB.NET is right above:
If (dr("DesireDays").ToString() = "127") Then
chkDaily.Checked = True
chkWeekly.Checked = False
chklstWeekly.Enabled = False
Else
chkWeekly.Checked = True
chkDaily.Checked = False
chklstWeekly.Enabled = True
Dim AD As Integer = dr("DesireDays").ToString()
Dim i As Integer
For i = 0 To chklstWeekly.Items.Count - 1
If AD And 2 ^ i Then
chklstWeekly.Items(i).Selected = True
End If
Next i
Any help will be appreciated.
You don't want to use ToDouble, as you want an int (that's what CInt gives you).
In addition, for doing powers of two, bitshifting is usually a little clearer than doing exponents (though choose whatever works for you).
As an aside, it's also usually safer to use a bitwise OR (the vertical | bar) rather than addition.
ListItem day = d as ListItem;
if (day.Selected)
{
daysBitmask |= 1 << Convert.ToInt32(day.Value);
}
To answer the actual question, the reverse will work:
ListItem day = d as ListItem;
if ((daysBitmask & (1 << Convert.ToInt32(day.Value))) > 0)
{
day.Selected = true;
}
加载中,请稍侯......
精彩评论