把这段代码转成c++或c

来源:百度知道 编辑:UC知道 时间:2024/05/22 15:14:32
function StrToBin(str)
dim curChr, curAsc, low, high
dim i
for i=1 To Len(str)
curChr = Mid(str, i, 1)
curAsc = Asc(curChr)
'asc对中文字符求出来的值可能为负数,
'加上65536就可求出它的无符号数值
'-1在机器内是用补码表示的0xffff,
'其无符号值为65535,65535=-1+65536
'其他负数依次类推。
if curAsc < 0 then
curAsc = curAsc + 65535
end if
'对中文的处理:把双字节低位和高位分开
if curAsc > 255 then
low = Left(Hex(Asc(curChr)), 2)
high = Right(Hex(Asc(curChr)), 2)
StrToBin = StrToBin & ChrB("&H" & low) & ChrB("&H" & high)
else
StrToBin = StrToBin & ChrB(AscB(CurChr))
end If
next
end function

#include <iostream>
#include <string>
using namespace std;

template <class T>
string StrToBin(T t);

// ASCii
template <>
string StrToBin(char c)
{
string temp;
for(int i = 0; i < 8; ++i)
{
if(c << i & 0x80)
temp.push_back('1');
else
temp.push_back('0');
}
return temp;
}

// Wide Character
template <>
string StrToBin(wchar_t wc)
{
string temp;
for(int i = 0; i < 16; ++i)
{
if(i == 8)
temp.push_back(' ');
if(wc << i & 0x8000)
temp.push_back('1');
else
temp.push_back('0');
}
return temp;
}

int main()
{
cout << StrToBin('1') << '\n';
cout << StrToBin(L'1') << '\n';
cout << StrToBi