十六進位制轉換為八進位制

___Evan發表於2014-02-23



#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 100005;
int n;
char Hex[maxn];
bool Bin[4*maxn];
int Oct[2*maxn];
int main()
{
    //freopen("data.txt","r",stdin);  
	int x;
	scanf("%d",&n);
	while( n -- )
	{
		scanf("%s",Hex);
		int hlen = strlen( Hex ),blen = 0,olen;
		for( int i = hlen-1; i >= 0; i -- ){
			if( Hex[i] >= 'A' )
				x = Hex[i] - 'A' + 10;
			else
				x = Hex[i] - '0';
			for( int j = 3; j >= 0; j -- ){
				Bin[blen++] = x%2;
				x /= 2;
			}
		}
		blen = hlen * 4;
		for( int i = 0; i < blen; i += 3 ){
			int num = 0,m = 1;
			for( int j = 0; j < 3 && i+j < blen; j ++ ){
				num += Bin[i+j] * m;
				m *= 2;
			}
			Oct[i/3] = num;
		}
		olen = blen/3+1;
		while( Oct[olen-1] == 0 && olen >= 0 )
			olen --;
		if( olen < 0 )
			printf("0");
		for( int i = olen-1; i >= 0; i -- )
			printf("%d",Oct[i]);
		puts("");
	}
    return 0;
}


#include <stdio.h>
 
int x2i(char c)
{
    if (c >= 'A')
        return c - 55;
    else
        return c - 48;
}
 
int main()
{
    int i, j, n;
    char a[10][100001];
    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%s", a[i]);
    for (i = 0; i < n; i++)
    {
        char* p = a[i];
        int len = strlen(p);
        if (len % 3 == 1)
        {
            printf("%o", x2i(p[0]));
            j = 1;
        }
        else if (len % 3 == 2)
        {
            printf("%o", x2i(p[0])*16+x2i(p[1]));
            j = 2;
        }
        else
        {
            printf("%o", x2i(p[0])*256+x2i(p[1])*16+x2i(p[2]));
            j = 3;
        }
        for (; j < len; j += 3)
            printf("%04o", x2i(p[j])*256+x2i(p[j+1])*16+x2i(p[j+2]));
        printf("\n");
    }
    return 0;
}


相關文章