簡體   English   中英

使用write()系統調用輸出char數組bufffer的dec / hex值

[英]Using write() system call to output dec/hex value of char array bufffer

int fd = open(argv[argc-1], O_RDONLY, 0);
 if (fd >=0) {
   char buff[4096]; //should be better sized based on stat
   ssize_t readBytes;
   int j;

   readBytes = read(fd, buff, 4096);

   char out[4096];
   for (j=0; buff[j] != '\0'; j++) {
     out[j] = buff[j];
     //printf("%d ", out[j]);
   }

   write(STDOUT_FILENO, out, j+1);

   close(fd);
}
 else {
   perror("File not opened.\n");
   exit(errno);
 }

這是文件轉儲程序的代碼。 目的是要有一個文件,並將其內容作為ASCII字符和十六進制/十進制值轉儲到命令行。 當前代碼能夠轉儲ascii值,但不能轉儲十六進制/十進制。 我們允許使用printf(如注釋部分中所示),但是如果我們不使用任何高級(高於系統)功能,我們將獲得額外的榮譽。 我已經嘗試了多種方法來在循環中操縱char數組,但是無論我如何嘗試添加或強制轉換它們作​​為char出來的char似乎都沒關系。

這並不奇怪,因為我知道char至少在C中是技術上的整數。 我不知道如何使用write()打印char的十六進制/ dec值,並且還沒有在堆棧上看到任何未默認為printf()或putchar()的答案

您可以制作一個更大的緩沖區,在其中進行從ASCII到十六進制/十進制的轉換(根據需要)並打印新的緩沖區。 我希望這個例子可以說明這個想法:

#include <stdlib.h>
#include <io.h>

int main (int argc, char** argv)
{
    const char* pHexLookup = "0123456789abcdef";
    char pBuffer[] = {'a', 'b', 'c'}; // Assume buffer is the contents of the file you have already read in
    size_t nInputSize = sizeof(pBuffer); // You will set this according to how much your input read in
    char* pOutputBuffer = (char*)malloc(nInputSize * 3); // This should be sufficient for hex, since it takes max 2 symbols, for decimal you should multiply by 4
    for (size_t nByte = 0; nByte < nInputSize; ++nByte)
    {
        pOutputBuffer[3 * nByte] = pBuffer[nByte];
        pOutputBuffer[3 * nByte + 1] = pHexLookup[pBuffer[nByte] / 16];
        pOutputBuffer[3 * nByte + 2] = pHexLookup[pBuffer[nByte] % 16];
    }
    write(1 /*STDOUT_FILENO*/, pOutputBuffer, nInputSize * 3);
    free(pOutputBuffer);
    return EXIT_SUCCESS;
}

這將a61b62c63打印a61b62c63 ,ASCII和十六進制值。

這是在Windows上完成的,因此不要嘗試直接復制它,我試圖堅持POSIX系統調用。 通常,對於十六進制,您分配的內存塊是原始內存塊的3倍(如果需要在輸出中加空格,則分配更大的內存塊),並在其旁邊放置一個與該字節的十六進制值相對應的ASCII符號。 對於十進制,您將需要更多空間,因為該值可以跨越3個字符。 然后只需編寫新的緩沖區。 希望這足夠清楚。

怎么樣:

unsigned char val;
val = *out / 100 + 48;
write(STDOUT_FILENO, &val, 1);
val = (*out - *out / 100 * 100 ) / 10 + 48;
write(STDOUT_FILENO, &val, 1);
val = (*out - *out / 10 * 10) + 48;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM