|
Hi,
this would be my approach in pseudo-code:
int result=0;
while(stringLength!=0) {
int oneByte=0;
int.TryParse(rightmost2characters, hexSpecifier, out=oneByte);
result=(result<<8)+oneByye;
drop2charsFromString;
}
<pre>
:)
<div class="ForumSig">Luc Pattyn <a href="http://www.codeproject.com/KB/scrapbook/ForumGuidelines.aspx">[Forum Guidelines]</a> <a href="http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=648011">[My Articles]</a>
<hr />Voting for dummies? No thanks. X|
<hr /></div>
|
|
|
|
|
I'd convert the hex digits into a byte array, figure out what your target Type is, pad/swap as necessary. 24 bit types are a curse on the land handed down from angry gods to punish us for the sins of BIT-BANGERS.... sorry....
class Program {
static void Main(string[] args) {
String s = "100000";
Byte[] temp = new Byte[4];
Array.Copy(GetBytes(s), 0, temp, 0, 3);
Int32 value = BitConverter.ToInt32(temp, 0);
Console.WriteLine(value.ToString());
Console.ReadLine();
}
public static byte[] GetBytes(string hexFormat) {
int byteLength = hexFormat.Length / 2;
byte[] bytes = new byte[byteLength];
for (int i = 0; i < byteLength; i++) {
bytes[i] = AsciiAsHexToByte(new String(new Char[] { hexFormat[i * 2], hexFormat[i * 2 + 1] }));
}
return bytes;
}
public static byte AsciiAsHexToByte(string hex) {
return byte.Parse(hex, NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo);
}
}
As you can see, it's a pain to do the conversion.
Scott P
“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.”
-Edsger Dijkstra
|
|
|
|
|
I'll 1/2 do your homework for ya
Imports System
Imports System.Globalization
Imports System.Text
Module Module1
Sub Main()
Dim sb As New StringBuilder("1C0000")
Dim str As String
Dim value As Integer
Dim bval As Byte
Dim j As Double
If (sb.Length Mod 2) = 1 Then
sb.Append("0")
End If
str = sb.ToString()
For i As Integer = 1 To str.Length Step 2
j = Math.Pow(16, Convert.ToDouble(i - 1))
bval = Byte.Parse(Mid(str, i, 2), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo)
value += Convert.ToInt32(Convert.ToDouble(bval) * j)
Next
Console.WriteLine("The string {0} is equal to {1}", sb.ToString(), value)
End Sub
End Module (doh! fixed logic typo)
-Spacix
All your skynet questions[ ^] belong to solved
I dislike the black-and-white voting system on questions/answers.
modified on Friday, June 20, 2008 4:25 PM
|
|
|
|
|
What's the other half? Converting it to C#?
I dislike the black-and-white voting system on questions/answers.
I agree that it's less nuanced, but on the other hand I see a huge increase in the usage of the voting system. It doesn't matter how good a system is, if noone uses it.
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
Guffa wrote: What's the other half? Converting it to C#?
You are correct sir!
There are a few other "optimizations" to be done which I would assume would garner a better grade from the original...
Guffa wrote: It doesn't matter how good a system is, if noone uses it.
aye, but I think the giant images is what made people start clicking it over the little "Rate this message: {thumb down vote 1} 1 2 3 4 5 {thumb up vote 5}"
-Spacix
All your skynet questions[ ^] belong to solved
I dislike the black-and-white voting system on questions/answers.
|
|
|
|
|
Hi,
I'm creating a C# application that will run in background and read the serial port. When any data comes from it, I'd like this application to set the text to the active application - it can be a field in the Internet Explorer or in the opened document in notepad. Is it possible in C#?
Thanks,
Dirso
|
|
|
|
|
you can get the active window using GetForegroundWindow function in User32.dll (check out PInvoke.net[^]). I'm not sure what will happen if the active window does't have a field selected that will accept the data you're sending! Also, the result can be NULL sometimes. Google for the function and you'll find loads of information.
Dave
|
|
|
|
|
Thanks! I already used this function once for Delphi application (anyway, I couldn't remember its name, so I marked your answer as helpful - since it really was ).
I also thought it could have some "cross plataform" C# native code or something, so I could compile with Mono as well, but looks like I'll have to use a few #ifdefs specific for each plataform right?
If you have any more ideas, for the cross plataform issue, I'll really appreciate.
Thanks again,
Dirso
|
|
|
|
|
Hi!
That's quite easy: There's a class SendKeys that simulates a sequence of keystrokes. Since keystrokes are routed to the currently selected control in the active application, this is what you want.
Regards,
mav
--
Black holes are the places where God divided by 0...
|
|
|
|
|
Hey all,
I'm looking for some tips on how to write an update manager for my application. This is what I have in mind and any suggestions on improvements are much appreciated as I'm putting this out of you-know-where.
When my application runs, instead of running the main program, run an "update manager" which just sends an HTTP request to my server to check which files are out of date, if any. The return from this trip to the server will contain the location of the files on my server. Then it will download these updates and run the application.
Firstly, does this open up my application to security threats?
Secondly, is this legal - I know other applications prompt the user before updating anything.
Thirdly, is there a way for the manager to update itself? I was thinking of something along the lines of another exe in the folder which is shelled and somehow knows when the first exe has closed and overwrites it, then relaunches it?
Again, any tips articles, best practices, etc are very much appreciated!
Mike
FREE 28 player online game @ http://www.1483online.com where the community drives enhancements to the game!
|
|
|
|
|
I do the same as you suggest and it works fine.
I simply call a webservice, that returns a version, if installed version below current, it open a prompt to ask the user to download it. Once ok is clicked, I simply download the install exe, and run that, while closing my application.
If the client does not want the application to access the internet, then they should have their own firewalls in place, that is not my concern.
|
|
|
|
|
Hi all.
I have a big XML file, part of that is like this :
<FoxMark>
<NODE ID="14" NAME="Utility" DESC="">
<NODE ID="16" NAME="Crack" DESC="">
<BOOKMARK ID="17" />
<BOOKMARK ID="18" />
<BOOKMARK ID="19" />
<BOOKMARK ID="20" />
<BOOKMARK ID="21" />
<BOOKMARK ID="22" />
</NODE>
</NODE>
</FoxMark>
Now, I want select <NODE ID="16" NAME="Crack" DESC=""> and delete it by LINQ.
I wrote this method but it wasn't work perfectly :
private void Delete(string id)
{
FileName = "file.xml";
try
{
XElement Xelement = XElement.Load(FileName);
var SelectedNode = from node in Xelement.Descendants("BOOKMARK")
where node.Attribute("ID").Value == id
select node;
if (SelectedNode.ToList().Count == 0)
SelectedNode = from node in Xelement.Descendants("NODE")
where node.Attribute("ID").Value == id
select node;
MessageBox.Show(SelectedNode.First().Name.ToString());
XElement Xnode = Xelement.Element(SelectedNode.First().Name);
Xnode.Remove();
Xelement.Save(FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Can you help me ?
Sorry for my English. I'm a freshman .
|
|
|
|
|
LINQ as it says in the name is a query language. You do not do deletions or insertions or updates with it.
|
|
|
|
|
Thanks leppie. I didn't know it.
But What's your suggestion to deleting specific node in my XML file ?
|
|
|
|
|
To be honest I have never used XLINQ, but your example looks ok (I really just being pedantic about your subject question ).
I just had a look at it, and I cannot see why you code should not work.
If I do see why, I will let you know
|
|
|
|
|
OK
All right.
Sorry for my English. I'm a freshman .
|
|
|
|
|
Who can help me ?
Sorry for my English. I'm a freshman .
|
|
|
|
|
I've highly modified the code found here http://www.codeproject.com/KB/IP/ChatAsynchTCPSockets.aspx.
When creating a packet, I give the following class the info it needs onto which is converts it into a byte[] and visa versa which can then be sent and received by a socket respectively.
public class Data
{
public Command cmdCommand;
public string strMessage;
public string strName;
public Data()
{
cmdCommand = Command.Null;
strMessage = null;
strName = null;
}
public Data(byte[] data)
{
cmdCommand = (Command)BitConverter.ToInt32(data, 0);
int nameLen = BitConverter.ToInt32(data, 4);
int msgLen = BitConverter.ToInt32(data, 8);
if (nameLen > 0)
strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
strName = null;
if (msgLen > 0)
strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
else
strMessage = null;
}
public byte[] ToByte()
{
List<byte> result = new List<byte>();
result.AddRange(BitConverter.GetBytes((int)cmdCommand));
if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));
if (strMessage != null)
result.AddRange(BitConverter.GetBytes(Encoding.UTF8.GetByteCount(strMessage)));
else
result.AddRange(BitConverter.GetBytes(0));
if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));
if (strMessage != null)
result.AddRange(Encoding.UTF8.GetBytes(strMessage));
return result.ToArray();
}
}</byte></byte>
However on some occasions of high traffic I get the following error:
Index and count must refer to a location within the buffer.
Parameter name: bytes
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
I feel the constructor which takes a byte array is the cause here. Can anyone suggest a better way of sending this data or point out the problem in the code which I cannot see? Help would be greatly appreciated.
|
|
|
|
|
Please fix the generics in the post. I am pretty sure that is a List of byte.
|
|
|
|
|
At which point do you get this error?
I suspect, the byte[] you pass to the constructor does not contain the correct data.
Add a check in the beginning of the constructor to ensure the byte[] is long enough at least.
|
|
|
|
|
As far as I can tell, I get the error after executing the following commands:
In the OnAccept method..
byte[] bufData = new byte[1024];
clientSocket.BeginReceive(bufData, 0, bufData.Length, SocketFlags.None, new AsyncCallback(OnReceive),
new object[] {clientSocket, bufData});
In the OnReceive method..
Socket clientSocket = null;
Data msgReceived = null;
byte[] bufData = new byte[1024];
bool bypass = false;
ClientInfo cInfo = null;
try
{
bool blInvalidClient = false;
try
{
object[] oData = (object[]) ar.AsyncState;
clientSocket = (Socket) oData[0];
bufData = (byte[]) oData[1];
clientSocket.EndReceive(ar);
}
catch (SocketException)
{
blInvalidClient = true;
}
if (!blInvalidClient)
{
msgReceived = Packet.PacketReceived(bufData);
...
The Packet.PacketReceived method returns new Data(bufData). I've added traces in that constructor and there is something incorrect happening. All clients that communicate use the same Data class to convert the info into a byte[] so it's not as if I'm sending an arb string of bytes to the socket.
But the weird thing is that this only ever happens when I sent lots of packets to the socket at once.
|
|
|
|
|
Problem seems to be here. Not sure I understand why...
if (nameLen > 0)
strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
strName = null;
|
|
|
|
|
It probably does not allow you to read zero strings (assuming it needs a 0 terminator).
|
|
|
|
|
Packets are lost due to this under high load. I'm out of ideas.
|
|
|
|
|
Hmmm. I increased the buffer size from 1024 to 4096 and everything seems to work perfectly now.
|
|
|
|