将字节数组转换为单个平面字节值



我有以下数组


byte[] SendBuff = new byte[262];
SendBuff[0] = 0x82;
SendBuff[1] = 0xD2;
SendBuff[2] = 0x00;
SendBuff[3] = Convert.ToByte(tAdd.Text.Substring(0, 2),16);
SendBuff[4] = Convert.ToByte(tLen.Text.Substring(0, 2),16);

我有以下函数来传递数据


SCardTransmit(hCard, ref sIO,ref SendBuff[0],SendBuffLen, ref sIO,ref RecvBuff[0],ref RecvBuffLen);
@param1 (int)
@param2 (ModWinsCard.SCARD_IO_REQUEST)
@param3 (buyte[])
@param4 (int)
@param5 (ModWinsCard.SCARD_IO_REQUEST)
@param6 (buyte[])
@param7 (int)

我想知道如何将所有数组数据作为单个字节传递到函数的第三个参数中,使

SendBuff[0]=SendBuff[1]、SendBuff[2]、SendBuffe[3]字节的组合


我还想知道如何将类似"88 00 1A 31 31"的字符串转换为字节并将其存储到SendBuff[0]中

我知道这听起来可能是重复,但我没能找到一个对我有用的解决方案。
有人请帮我,我正在努力
提前感谢


解释
我正在为智能卡开发并向读卡器发送命令,但需要命令(APDU)具有以下字符串
4字节标头(CLA、INS、P1、P2),例如"88 D2 00 01 02">

该命令通过函数的param3作为字节传递给上述函数。所以我想知道如何将该命令传递给那个param3。谢谢,希望这个解释能有所帮助。

做出这些假设:

  1. 您列出的SCardTransmit方法不是该方法的声明,而是实际用于调用它的代码
  2. 您在@param1-7项列表中为我们提供了用于调用方法的变量类型

如果第三个参数是byte[](字节数组),则不应该传入SendBuff[0]。这实际上只是传入一个字节,即位于索引0处的字节。您要发送整个数组。因此,您的呼叫代码为:

SCardTransmit(hCard, ref sIO, ref SendBuff, SendBuffLen, ref sIO, ref RecvBuff, ref RecvBuffLen);

注意:我对SendBuff和RecvBuff做了同样的事情。


关于将字符串转换为字节的第二个问题,看起来像是在使用Convert.ToByte(tAdd.Text.Substring(0, 2),16);

你想要的是一个转换它的循环。你可以通过空格字符将字符串拆分成一个子字符串数组,你可以迭代并转换每个字节。这是实现这一点的代码:

string stringOfBytes = "88 00 1A 31 31 31";
string[] stringBytes = stringOfBytes.Split(' ');
byte[] outputBytes = new byte[stringBytes.Length];
for (int i = 0; i < stringBytes.Length; i++)
{
outputBytes[i] = Convert.ToByte(stringBytes[i], 16);
}

SCardTransmit的签名不正确。在pinvoke.net中,您可以看到正确的签名,以及如何使用它的示例代码:http://pinvoke.net/default.aspx/winscard/SCardTransmit.html\

[DllImport("winscard.dll")]
public static extern int SCardTransmit(int hCard, ref SCARD_IO_REQUEST pioSendRequest, ref byte SendBuff, int SendBuffLen, ref SCARD_IO_REQUEST pioRecvRequest,
ref byte RecvBuff, ref int RecvBuffLen);

对于您的请求,您可以用这样的东西调用函数(假设_hCard是对SCardConnect调用返回的引用(注意,这会丢弃返回的值):

[StructLayout(LayoutKind.Sequential)]
public struct SCARD_IO_REQUEST
{
internal uint dwProtocol;
internal int cbPciLength;
}
SCARD_IO_REQUEST request = new SCARD_IO_REQUEST();
request.dwProtocol = 1; // This is SCARD_PROTOCOL_T1, sub with whatever protocol you're using
request.cbPciLength = System.Runtime.InteropServices.Marshal.SizeOf(typeof(SCARD_IO_REQUEST));
SCardTransmit(_hCard, ref request, ref SendBuff, SendBuff.Length, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

有关本机呼叫的更多信息,请访问此处:http://msdn.microsoft.com/en-us/library/windows/desktop/aa379804%28v=vs.85%29.aspx你可以使用pinvoke.net来获得更多关于其他类似功能的帮助。

最新更新