プロが教えるわが家の防犯対策術!

"1234567"という文字列を
パック10進数に変換したいのですが、
どのようにしたら良いのでしょうか?

まず左に4bitシフトさせてから符号部分の4bitを
うまく取り除ければ出来ると思うのですが、どう実装したら良いか分かりません。

よろしくお願いします。

A 回答 (3件)

#2です。

入力文字のサイズと変換結果を格納するサイズを指定して、変換を行いたいように見えましたので、そのように修正しました。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void topack(int len1,char *str1,int len2,char *str2)
{
//len1:入力文字列長
//str1:入力文字
//len2:出力結果長
//str2:出力結果
int s1 = 0;
int i;
char x;
memset(str2,0x00,len2);
for (i=0;i<len2;i++){
s1++;
if (s1 >len1) break;
x = *str1++ & 0x0f;
x = x << 4;
s1++;
if (s1<=len1){
x |= *str1++ &0x0f;
}
*str2++ = x;
}
}
int main()
{
unsigned char out[8];
memset(out,0xff,sizeof(out));
topack(7,"12345679875",4,out);
printf ("out=%02x%02x%02x%02x%02x%02x%02x%02x\n",
out[0],out[1],out[2],out[3],out[4],out[5],out[6],out[7]);
memset(out,0xff,sizeof(out));
topack(8,"12345678777",3,out);
printf ("out=%02x%02x%02x%02x%02x%02x%02x%02x\n",
out[0],out[1],out[2],out[3],out[4],out[5],out[6],out[7]);
topack(3,"12345678777",4,out);
printf ("out=%02x%02x%02x%02x%02x%02x%02x%02x\n",
out[0],out[1],out[2],out[3],out[4],out[5],out[6],out[7]);
return 0;
}
    • good
    • 1
この回答へのお礼

ありがとうございます。
こちらの方を参考にカズタマイズしながら勉強します。

お礼日時:2005/02/25 09:11

以下は、入力文字列をパックに変換する関数:topackです。


---------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void topack(char *str1,char *str2)
{
//str1:入力文字(終端NULLであること)
//str2:出力結果
int s1 = strlen(str1);
int s2 = (s1+1)/2;
int i;
char x;
for (i=0;i<s2;i++){
x = *str1++ & 0x0f;
x = x << 4;
x |= *str1++ &0x0f;
*str2++ = x;
}
}
int main()
{
unsigned char out[8];
memset(out,0xff,sizeof(out));
topack("1234567",out);
printf ("out=%02x%02x%02x%02x%02x%02x%02x%02x\n",
out[0],out[1],out[2],out[3],out[4],out[5],out[6],out[7]);
memset(out,0xff,4);
topack("12345678",out);
printf ("out=%02x%02x%02x%02x%02x%02x%02x%02x\n",
out[0],out[1],out[2],out[3],out[4],out[5],out[6],out[7]);
return 0;
}


---------------------------------
    • good
    • 0

"1234567"という文字列を変換したとき、期待する結果は、次のいずれですか?


1.0x12,0x34,0x56,0x70 の4バイト
2.0x01,0x23,0x45,0x67 の4バイト
3.上記以外(この場合は具体例を提示して下さい)

この回答への補足

返信有難う御座います。
期待している結果は1です。

現在のソースを以下に張ります。
このソースで期待した値が返ってきたので、
一応は解決したのですが、他に方法がありましたら
参考にさせていただきたく思います。


#include <stdlib.h>
#include <string.h>

int func();
char str1[]={'1','2','3','4','5','6','7'};
char str2[4];

int main(void)
{
int val=0;
val = func();
return 0;
}

int func()
{
int j,k=0;
int size1=sizeof(str1);
int size2=sizeof(str2);

for(j=0;j<size1;j++)
{
if(j%2==0)
{
str2[k] = (str1[j] - 0x30) << 4;
}else{
str2[k] = str1[j] | (str1[j] - 0x30);
k++;
}
}

if(size1%2 != 0)
{
str2[size2-1] = str1[size1-1] | 0x03;
}
return atoi(str2);
}

補足日時:2005/02/24 20:25
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!

このQ&Aを見た人はこんなQ&Aも見ています