从文件中读取十六进制

时间:2017-10-19 05:15:06

标签: c

所以我对指针的了解有点生疏,我认为这就是我搞砸了,我正在尝试编写一个函数来获取文件中指定偏移量的十六进制值(数量n) 。并将这些值写入数组。

文件我正在阅读,示例

        0  1  2  3  4  5  6  7      8  9  A  B  C  D  E  F
   0   F6 EA 9D DE D8 40 1C 44     19 24 59 D2 6A 2C 48 1D
   1   FC 96 DE 94 AF 95 FC 42     9B 6D DA 15 D4 CE 88 BB
   2   B8 24 99 8F 65 B5 D3 7E     D9 5D 51 44 89 97 61 85
   3   2D 40 1A DC D5 16 1F 70     84 F9 85 58 C8 0E 13 80
   4   32 AC 10 97 61 B3 16 3B     40 67 7A CA FE E1 4F 2B
   5   21 A9 07 F6 80 26 66 04     20 EC 5C E8 FA 70 68 2C
   6   1C 78 C4 7E 5C DA B9 9C     41 38 66 3F 19 B6 6A 3A

这是我迄今为止所写的功能。

adest指向大小为nBytes + 1

的数组

bAddr指向内存区域的第一个字节

OffsetAmt是一个相对bAddr

的位置

nBytes只是我要复制的字节数

继承人的职能

void getHexBytesAt(uint8_t* const aDest, const uint8_t* const bAddr,
                                          uint16_t OffsetAmt, uint8_t nBytes)
{
    const uint8_t *point1 = bAddr; //set he address of point1 to base address  value

//front point1 shift until we get to the specified offset value
    for (int i = 0; i < Offset; i++)
    {
       point1 = (point1 + 1);
    }

//set the values of *aDest to the value of point1;
//increment point1
    for (int k = 0; k < nBytes; k++)
    {
       *aDest = point1;
        point1 = (point1 + 1);
    }   

我遇到的问题是我甚至没有正确地将第一个字节复制到数组中,

我的输出看起来像这个获取9个字节, 从偏移2C开始

MY OUTPUT: 84 CA CA CA CA CA CA CA CA 
FILE: 89 97 61 85 2D 40 1A DC D5

1 个答案:

答案 0 :(得分:2)

如果要从Memory bAddr读取数据,则必须

  • 取消引用阅读指针
  • 递增目标指针

这将实现如下:

void getHexBytesAt(uint8_t* const aDest, const uint8_t* const bAddr,
                                          uint16_t OffsetAmt, uint8_t nBytes)
{
    const uint8_t *point1 = bAddr; //set he address of point1 to base address  value

//front point1 shift until we get to the specified offset value
    for (int i = 0; i < OffsetAmt; i++)  // fixed typo
    {
       point1 = (point1 + 1);
    }

//set the values of *aDest to the value of point1;
//increment point1
    for (int k = 0; k < nBytes; k++)
    {
       *aDest = *point1;     // copy data from address the point1 points to
        aDest = aDest + 1;   // increment destination pointer
        point1 = (point1 + 1);
    }   
}

但这可以做得更简单:

void getHexBytesAt(uint8_t* const aDest, const uint8_t* const bAddr,
                                          uint16_t OffsetAmt, uint8_t nBytes)
{
    memcpy(aDest, bAddr + OffsetAmt, nBytes);
}

您应该考虑使用在代码中实现它的单行替换该函数。

BTW:代码中没有使用文件。你应该检查你的问题。

相关问题